File: timestamp_test.go

package info (click to toggle)
golang-github-google-cel-go 0.18.2%2Bds-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,888 kB
  • sloc: sh: 93; makefile: 12
file content (487 lines) | stat: -rw-r--r-- 14,940 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package types

import (
	"errors"
	"math"
	"reflect"
	"testing"
	"time"

	"github.com/google/cel-go/common/overloads"
	"github.com/google/cel-go/common/types/ref"

	"google.golang.org/protobuf/proto"

	anypb "google.golang.org/protobuf/types/known/anypb"
	structpb "google.golang.org/protobuf/types/known/structpb"
	tpb "google.golang.org/protobuf/types/known/timestamppb"
)

func TestTimestampConvertToType(t *testing.T) {
	ts := Timestamp{Time: time.Unix(7654, 321).UTC()}
	if ts.ConvertToType(TypeType) != TimestampType {
		t.Errorf("ConvertToType(type) failed to return timestamp type: %v", ts.ConvertToType(TypeType))
	}
	if ts.ConvertToType(IntType) != Int(7654) {
		t.Errorf("ConvertToType(int) failed to truncate a timestamp to a unix epoch: %v", ts.ConvertToType(IntType))
	}
	if ts.ConvertToType(StringType) != String("1970-01-01T02:07:34.000000321Z") {
		t.Errorf("ConvertToType(string) failed to convert to a human readable timestamp. "+
			"got %v, wanted: 1970-01-01T02:07:34.000000321Z",
			ts.ConvertToType(StringType))
	}
	if ts.ConvertToType(TimestampType) != ts {
		t.Error("ConvertToType(timestamp) failed an identity conversion")
	}
	if !IsError(ts.ConvertToType(DurationType)) {
		t.Error("ConvertToType(duration) failed to error")
	}
}

func TestTimestampOperators(t *testing.T) {
	unixTimestamp := func(epoch int64) Timestamp {
		return timestampOf(time.Unix(epoch, 0).UTC())
	}
	tests := []struct {
		name string
		op   func() ref.Val
		out  any
	}{
		// Addition tests.
		{
			name: "DateAddOneHourMinusOneMilli",
			op: func() ref.Val {
				return unixTimestamp(3506).Add(durationOf(time.Hour - time.Millisecond))
			},
			out: time.Unix(7106, 0).Add(-time.Millisecond).UTC(),
		},
		{
			name: "DateAddOneHourOneNano",
			op: func() ref.Val {
				return unixTimestamp(3506).Add(durationOf(time.Hour + time.Nanosecond))
			},
			out: time.Unix(7106, 1).UTC(),
		},
		{
			name: "IntMaxAddOneSecond",
			op: func() ref.Val {
				return unixTimestamp(math.MaxInt64).Add(durationOf(time.Second))
			},
			out: errIntOverflow,
		},
		{
			name: "MaxTimestampAddOneSecond",
			op: func() ref.Val {
				return unixTimestamp(maxUnixTime).Add(durationOf(time.Second))
			},
			out: errTimestampOverflow,
		},
		{
			name: "MaxIntAddOneViaNanos",
			op: func() ref.Val {
				return timestampOf(time.Unix(math.MaxInt64, 999_999_999).UTC()).Add(durationOf(time.Nanosecond))
			},
			out: errIntOverflow,
		},
		{
			name: "SecondsWithNanosNegative",
			op: func() ref.Val {
				ts1 := unixTimestamp(1).Add(durationOf(time.Nanosecond)).(Timestamp)
				return ts1.Add(durationOf(-999_999_999))
			},
			out: time.Unix(0, 2).UTC(),
		},
		{
			name: "SecondsWithNanosPositive",
			op: func() ref.Val {
				ts1 := unixTimestamp(1).Add(durationOf(999_999_999 * time.Nanosecond)).(Timestamp)
				return ts1.Add(durationOf(999_999_999))
			},
			out: time.Unix(2, 999_999_998).UTC(),
		},
		{
			name: "DateAddDateError",
			op: func() ref.Val {
				return unixTimestamp(1).Add(unixTimestamp(1))
			},
			out: errors.New("no such overload"),
		},

		// Comparison tests.
		{
			name: "DateCompareEqual",
			op: func() ref.Val {
				return unixTimestamp(1).Compare(unixTimestamp(1))
			},
			out: int64(0),
		},
		{
			name: "DateCompareBefore",
			op: func() ref.Val {
				return unixTimestamp(1).Compare(unixTimestamp(200))
			},
			out: int64(-1),
		},
		{
			name: "DateCompareAfter",
			op: func() ref.Val {
				return unixTimestamp(1000).Compare(unixTimestamp(200))
			},
			out: int64(1),
		},
		{
			name: "DateCompareError",
			op: func() ref.Val {
				return unixTimestamp(1000).Compare(durationOf(1000))
			},
			out: errors.New("no such overload"),
		},

		// Time subtraction tests.
		{
			name: "TimeSubOneSecond",
			op: func() ref.Val {
				return unixTimestamp(100).Subtract(unixTimestamp(1))
			},
			out: 99 * time.Second,
		},
		{
			name: "DateSubOneHour",
			op: func() ref.Val {
				return unixTimestamp(3506).Subtract(durationOf(time.Hour))
			},
			out: time.Unix(-94, 0).UTC(),
		},
		{
			name: "MinTimestampSubOneSecond",
			op: func() ref.Val {
				return unixTimestamp(-62135596800).Subtract(durationOf(time.Second))
			},
			out: errTimestampOverflow,
		},
		{
			name: "MinTimestampSubMinusOneViaNanos",
			op: func() ref.Val {
				return timestampOf(time.Unix(-62135596800, 2).UTC()).Subtract(durationOf(-999_999_999 * time.Nanosecond))
			},
			out: time.Unix(-62135596799, 1).UTC(),
		},
		{
			name: "MinIntSubOneViaNanosOverflow",
			op: func() ref.Val {
				return timestampOf(time.Unix(math.MinInt64, 0).UTC()).Subtract(durationOf(time.Nanosecond))
			},
			out: errIntOverflow,
		},
		{
			name: "TimeWithNanosPositive",
			op: func() ref.Val {
				return timestampOf(time.Unix(2, 1)).Subtract(timestampOf(time.Unix(0, 999_999_999)))
			},
			out: time.Second + 2*time.Nanosecond,
		},
		{
			name: "TimeWithNanosNegative",
			op: func() ref.Val {
				return timestampOf(time.Unix(1, 1)).Subtract(timestampOf(time.Unix(2, 999_999_999)))
			},
			out: -2*time.Second + 2*time.Nanosecond,
		},
		{
			name: "MinTimestampMinusOne",
			op: func() ref.Val {
				return unixTimestamp(math.MinInt64).Subtract(unixTimestamp(1))
			},
			out: errIntOverflow,
		},
		{
			name: "DateMinusDateDurationOverflow",
			op: func() ref.Val {
				return unixTimestamp(maxUnixTime).Subtract(unixTimestamp(minUnixTime))
			},
			out: errIntOverflow,
		},
		{
			name: "MinTimestampMinusOneViaNanosScaleOverflow",
			op: func() ref.Val {
				return timestampOf(time.Unix(math.MinInt64, 1)).Subtract(timestampOf(time.Unix(0, -999_999_999)))
			},
			out: errIntOverflow,
		},
		{
			name: "DateSubMinDuration",
			op: func() ref.Val {
				return unixTimestamp(1).Subtract(durationOf(math.MinInt64))
			},
			out: errIntOverflow,
		},
	}
	for _, tst := range tests {
		got := tst.op()
		switch v := got.Value().(type) {
		case time.Time:
			if want, ok := tst.out.(time.Time); !ok || !v.Equal(want) {
				t.Errorf("%s: got %v, wanted %v", tst.name, v, tst.out)
			}
		case error:
			if want, ok := tst.out.(error); !ok || v.Error() != want.Error() {
				t.Errorf("%s: got %v, wanted %v", tst.name, v, tst.out)
			}
		default:
			if !reflect.DeepEqual(v, tst.out) {
				t.Errorf("%s: got %v, wanted %v", tst.name, v, tst.out)
			}
		}
	}
}

func TestTimestampConvertToNative_Any(t *testing.T) {
	// 1970-01-01T02:05:06Z
	ts := Timestamp{Time: time.Unix(7506, 0)}
	val, err := ts.ConvertToNative(anyValueType)
	if err != nil {
		t.Error(err)
	}
	want, err := anypb.New(tpb.New(ts.Time))
	if err != nil {
		t.Error(err)
	}
	if !proto.Equal(val.(proto.Message), want) {
		t.Errorf("Got '%v', expected '%v'", val, want)
	}
}

func TestTimestampConvertToNative(t *testing.T) {
	// 1970-01-01T02:05:06Z
	ts := Timestamp{Time: time.Unix(7506, 0).UTC()}
	val, err := ts.ConvertToNative(timestampValueType)
	if err != nil {
		t.Error(err)
	}
	var want any
	want = tpb.New(ts.Time)
	if !proto.Equal(val.(proto.Message), want.(proto.Message)) {
		t.Errorf("Got '%v', expected '%v'", val, want)
	}
	val, err = ts.ConvertToNative(jsonValueType)
	if err != nil {
		t.Error(err)
	}
	want = structpb.NewStringValue("1970-01-01T02:05:06Z")
	if !proto.Equal(val.(proto.Message), want.(proto.Message)) {
		t.Errorf("Got '%v', expected '%v'", val, want)
	}
	val, err = ts.ConvertToNative(anyValueType)
	if err != nil {
		t.Error(err)
	}
	want, err = anypb.New(tpb.New(ts.Time))
	if err != nil {
		t.Error(err)
	}
	if !proto.Equal(val.(proto.Message), want.(proto.Message)) {
		t.Errorf("Got '%v', expected '%v'", val, want)
	}
	val, err = ts.ConvertToNative(reflect.TypeOf(Timestamp{}))
	if err != nil {
		t.Error(err)
	}
	if !reflect.DeepEqual(val, ts) {
		t.Errorf("got %v wanted %v", val, ts)
	}
	val, err = ts.ConvertToNative(reflect.TypeOf(time.Now()))
	if err != nil {
		t.Error(err)
	}
	want = time.Unix(7506, 0).UTC()
	if !reflect.DeepEqual(val, want) {
		t.Errorf("got %v wanted %v", val, want)
	}
}

func TestTimestampIsZeroValue(t *testing.T) {
	if (Timestamp{Time: time.Now()}).IsZeroValue() {
		t.Error("Timestamp(Now()).IsZeroValue() returned true, wanted false.")
	}
	if (Timestamp{Time: time.Unix(0, 0)}).IsZeroValue() {
		t.Error("Timestamp(0).IsZeroValue() returned true, wanted false.")
	}
}

func TestTimestampGetDayOfMonth(t *testing.T) {
	// 1970-01-01T02:05:06Z
	ts := timestampOf(time.Unix(7506, 0).UTC())
	mon := ts.Receive(overloads.TimeGetDayOfMonth, overloads.TimestampToDayOfMonthZeroBased, []ref.Val{})
	if !mon.Equal(Int(0)).(Bool) {
		t.Errorf("ts.getDayOfMonth() got %v, wanted 0", mon)
	}
	// 1969-12-31T19:05:06Z
	monTz := ts.Receive(overloads.TimeGetDayOfMonth, overloads.TimestampToDayOfMonthZeroBasedWithTz,
		[]ref.Val{String("America/Phoenix")})
	if !monTz.Equal(Int(30)).(Bool) {
		t.Errorf("ts.getDayOfMonth() got %v, wanted 30", mon)
	}
	// 1969-12-31T19:05:06Z
	monTz = ts.Receive(overloads.TimeGetDayOfMonth, overloads.TimestampToDayOfMonthZeroBasedWithTz,
		[]ref.Val{String("-07:00")})
	if !monTz.Equal(Int(30)).(Bool) {
		t.Errorf("ts.getDayOfMonth() got %v, wanted 30", mon)
	}

	// 1970-01-01T02:05:06Z
	mon = ts.Receive(overloads.TimeGetDate, overloads.TimestampToDayOfMonthOneBased, []ref.Val{})
	if !mon.Equal(Int(1)).(Bool) {
		t.Errorf("ts.getDate() got %v, wanted 1", mon)
	}
	// 1969-12-31T19:05:06Z
	monTz = ts.Receive(overloads.TimeGetDate, overloads.TimestampToDayOfMonthOneBasedWithTz,
		[]ref.Val{String("America/Phoenix")})
	if !monTz.Equal(Int(31)).(Bool) {
		t.Errorf("ts.getDate() got %v, wanted 31", mon)
	}
	// 1970-01-02T01:05:06Z
	monTz = ts.Receive(overloads.TimeGetDate, overloads.TimestampToDayOfMonthOneBasedWithTz,
		[]ref.Val{String("+23:00")})
	if !monTz.Equal(Int(2)).(Bool) {
		t.Errorf("ts.getDate() got %v, wanted 2", mon)
	}
}

func TestTimestampGetDayOfYear(t *testing.T) {
	// 1970-01-01T02:05:06Z
	ts := timestampOf(time.Unix(7506, 0).UTC())
	hr := ts.Receive(overloads.TimeGetDayOfYear, overloads.TimestampToDayOfYear, []ref.Val{})
	if !hr.Equal(Int(0)).(Bool) {
		t.Error("Expected 0, got", hr)
	}
	// 1969-12-31T19:05:06Z
	hrTz := ts.Receive(overloads.TimeGetDayOfYear, overloads.TimestampToDayOfYearWithTz,
		[]ref.Val{String("America/Phoenix")})
	if !hrTz.Equal(Int(364)).(Bool) {
		t.Error("Expected 364, got", hrTz)
	}
	hrTz = ts.Receive(overloads.TimeGetDayOfYear, overloads.TimestampToDayOfYearWithTz,
		[]ref.Val{String("-07:00")})
	if !hrTz.Equal(Int(364)).(Bool) {
		t.Error("Expected 364, got", hrTz)
	}
}

func TestTimestampGetFullYear(t *testing.T) {
	// 1970-01-01T02:05:06Z
	ts := Timestamp{Time: time.Unix(7506, 0).UTC()}
	year := ts.Receive(overloads.TimeGetFullYear, overloads.TimestampToYear, []ref.Val{})
	if !year.Equal(Int(1970)).(Bool) {
		t.Errorf("ts.getFullYear() got %v, wanted 1970", year)
	}
	// 1969-12-31T19:05:06Z
	yearTz := ts.Receive(overloads.TimeGetFullYear, overloads.TimestampToYearWithTz,
		[]ref.Val{String("America/Phoenix")})
	if !yearTz.Equal(Int(1969)).(Bool) {
		t.Errorf("ts.getFullYear('America/Phoenix') got %v, wanted 1969", yearTz)
	}
}

func TestTimestampGetMonth(t *testing.T) {
	// 1970-01-01T02:05:06Z
	ts := Timestamp{Time: time.Unix(7506, 0).UTC()}
	hr := ts.Receive(overloads.TimeGetMonth, overloads.TimestampToMonth, []ref.Val{})
	if !hr.Equal(Int(0)).(Bool) {
		t.Errorf("ts.getMonth() got %v, wanted 0", hr)
	}
	// 1969-12-31T19:05:06Z
	hrTz := ts.Receive(overloads.TimeGetMonth, overloads.TimestampToMonthWithTz,
		[]ref.Val{String("America/Phoenix")})
	if !hrTz.Equal(Int(11)).(Bool) {
		t.Errorf("ts.getMonth('America/Phoenix') got %v, wanted 11", hrTz)
	}
}

func TestTimestampGetDayOfWeek(t *testing.T) {
	// 1970-01-01T02:05:06Z
	ts := Timestamp{Time: time.Unix(7506, 0).UTC()}
	day := ts.Receive(overloads.TimeGetDayOfWeek, overloads.TimestampToDayOfWeek, []ref.Val{})
	if !day.Equal(Int(4)).(Bool) {
		t.Errorf("ts.getDayOfWeek() got %v, wanted 4", day)
	}
	// 1969-12-31T19:05:06Z
	dayTz := ts.Receive(overloads.TimeGetDayOfWeek, overloads.TimestampToDayOfWeekWithTz,
		[]ref.Val{String("America/Phoenix")})
	if !dayTz.Equal(Int(3)).(Bool) {
		t.Errorf("ts.getDayOfWeek('America/Phoenix') got %v, wanted 3", dayTz)
	}
}

func TestTimestampGetHours(t *testing.T) {
	// 1970-01-01T02:05:06Z
	ts := Timestamp{Time: time.Unix(7506, 0).UTC()}
	hr := ts.Receive(overloads.TimeGetHours, overloads.TimestampToHours, []ref.Val{})
	if !hr.Equal(Int(2)).(Bool) {
		t.Errorf("ts.getHours() got %v, wanted 2", hr)
	}
	// 1969-12-31T19:05:06Z
	hrTz := ts.Receive(overloads.TimeGetHours, overloads.TimestampToHoursWithTz,
		[]ref.Val{String("America/Phoenix")})
	if !hrTz.Equal(Int(19)).(Bool) {
		t.Errorf("ts.getHours('America/Phoenix') got %v, wanted 19 hours", hrTz)
	}
}

func TestTimestampGetMinutes(t *testing.T) {
	// 1970-01-01T02:05:06Z
	ts := Timestamp{Time: time.Unix(7506, 0).UTC()}
	min := ts.Receive(overloads.TimeGetMinutes, overloads.TimestampToMinutes, []ref.Val{})
	if !min.Equal(Int(5)).(Bool) {
		t.Errorf("ts.getMinutes() got %v, wanted 5 minutes", min)
	}
	// 1969-12-31T19:05:06Z
	minTz := ts.Receive(overloads.TimeGetMinutes, overloads.TimestampToMinutesWithTz,
		[]ref.Val{String("America/Phoenix")})
	if !minTz.Equal(Int(5)).(Bool) {
		t.Errorf("ts.getMinutes('America/Phoenix') got %v, wanted 5 minutes", min)
	}
}

func TestTimestampGetSeconds(t *testing.T) {
	// 1970-01-01T02:05:06Z
	ts := Timestamp{Time: time.Unix(7506, 0).UTC()}
	sec := ts.Receive(overloads.TimeGetSeconds, overloads.TimestampToSeconds, []ref.Val{})
	if !sec.Equal(Int(6)).(Bool) {
		t.Errorf("ts.getSeconds() got %v, wanted 6 seconds", sec)
	}
	// 1969-12-31T19:05:06Z
	secTz := ts.Receive(overloads.TimeGetSeconds, overloads.TimestampToSecondsWithTz,
		[]ref.Val{String("America/Phoenix")})
	if !secTz.Equal(Int(6)).(Bool) {
		t.Errorf("ts.getSeconds('America/Phoenix') got %v, wanted 6 seconds", secTz)
	}
}

func TestTimestampGetMilliseconds(t *testing.T) {
	// 1970-01-01T02:05:06Z
	ts := Timestamp{Time: time.Unix(7506, 1000000).UTC()}
	ms := ts.Receive(overloads.TimeGetMilliseconds, overloads.TimestampToMilliseconds, []ref.Val{})
	if !ms.Equal(Int(1)).(Bool) {
		t.Errorf("ts.getMilliseconds() got %v, wanted 1 ms", ms)
	}
	// 1969-12-31T19:05:06Z
	msTz := ts.Receive(overloads.TimeGetMilliseconds, overloads.TimestampToMillisecondsWithTz,
		[]ref.Val{String("America/Phoenix")})
	if !msTz.Equal(Int(1)).(Bool) {
		t.Errorf("ts.getMilliseconds('America/Phoenix') got %v, wanted 1 ms", msTz)
	}
}