go.starlark.net@v0.0.0-20231101134539-556fd59b42f6/lib/time/time_test.go (about) 1 package time 2 3 import ( 4 "errors" 5 "testing" 6 "time" 7 8 "go.starlark.net/starlark" 9 ) 10 11 func TestPerThreadNowReturnsCorrectTime(t *testing.T) { 12 th := &starlark.Thread{} 13 date := time.Date(1, 2, 3, 4, 5, 6, 7, time.UTC) 14 SetNow(th, func() (time.Time, error) { 15 return date, nil 16 }) 17 18 res, err := starlark.Call(th, Module.Members["now"], nil, nil) 19 if err != nil { 20 t.Fatal(err) 21 } 22 23 retTime := time.Time(res.(Time)) 24 25 if !retTime.Equal(date) { 26 t.Fatal("Expected time to be equal", retTime, date) 27 } 28 } 29 30 func TestPerThreadNowReturnsError(t *testing.T) { 31 th := &starlark.Thread{} 32 e := errors.New("no time") 33 SetNow(th, func() (time.Time, error) { 34 return time.Time{}, e 35 }) 36 37 _, err := starlark.Call(th, Module.Members["now"], nil, nil) 38 if !errors.Is(err, e) { 39 t.Fatal("Expected equal error", e, err) 40 } 41 } 42 43 func TestGlobalNowReturnsCorrectTime(t *testing.T) { 44 th := &starlark.Thread{} 45 46 oldNow := NowFunc 47 defer func() { 48 NowFunc = oldNow 49 }() 50 51 date := time.Date(1, 2, 3, 4, 5, 6, 7, time.UTC) 52 NowFunc = func() time.Time { 53 return date 54 } 55 56 res, err := starlark.Call(th, Module.Members["now"], nil, nil) 57 if err != nil { 58 t.Fatal(err) 59 } 60 61 retTime := time.Time(res.(Time)) 62 63 if !retTime.Equal(date) { 64 t.Fatal("Expected time to be equal", retTime, date) 65 } 66 } 67 68 func TestGlobalNowReturnsErrorWhenNil(t *testing.T) { 69 th := &starlark.Thread{} 70 71 oldNow := NowFunc 72 defer func() { 73 NowFunc = oldNow 74 }() 75 76 NowFunc = nil 77 78 _, err := starlark.Call(th, Module.Members["now"], nil, nil) 79 if err == nil { 80 t.Fatal("Expected to get an error") 81 } 82 }