go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/clock/clockflag/time_test.go (about)

     1  // Copyright 2015 The LUCI Authors.
     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 clockflag
    16  
    17  import (
    18  	"encoding/json"
    19  	"flag"
    20  	"testing"
    21  	"time"
    22  
    23  	. "github.com/smartystreets/goconvey/convey"
    24  )
    25  
    26  func TestTime(t *testing.T) {
    27  	t.Parallel()
    28  
    29  	Convey(`A Time flag`, t, func() {
    30  		fs := flag.NewFlagSet("test", flag.ContinueOnError)
    31  		var d Time
    32  		fs.Var(&d, "time", "Test time parameter.")
    33  
    34  		Convey(`Parses a 10-second Time from "2015-05-05T23:47:17+00:00".`, func() {
    35  			err := fs.Parse([]string{"-time", "2015-05-05T23:47:17+00:00"})
    36  			So(err, ShouldBeNil)
    37  			So(d.Time().Equal(time.Unix(1430869637, 0)), ShouldBeTrue)
    38  		})
    39  
    40  		Convey(`Returns an error when parsing "asdf".`, func() {
    41  			err := fs.Parse([]string{"-time", "asdf"})
    42  			So(err, ShouldNotBeNil)
    43  		})
    44  
    45  		Convey(`When treated as a JSON field`, func() {
    46  			var s struct {
    47  				T Time `json:"time"`
    48  			}
    49  
    50  			testJSON := `{"time":"asdf"}`
    51  			Convey(`Fails to unmarshal from `+testJSON+`.`, func() {
    52  				testJSON := testJSON
    53  				err := json.Unmarshal([]byte(testJSON), &s)
    54  				So(err, ShouldNotBeNil)
    55  			})
    56  
    57  			Convey(`Marshals correctly to RFC3339 time string.`, func() {
    58  				s.T = Time(time.Unix(1430869637, 0))
    59  				testJSON, err := json.Marshal(&s)
    60  				So(err, ShouldBeNil)
    61  				So(string(testJSON), ShouldEqual, `{"time":"2015-05-05T23:47:17Z"}`)
    62  
    63  				Convey(`And Unmarshals correctly.`, func() {
    64  					s.T = Time{}
    65  					err := json.Unmarshal([]byte(testJSON), &s)
    66  					So(err, ShouldBeNil)
    67  					So(s.T.Time().Equal(time.Unix(1430869637, 0)), ShouldBeTrue)
    68  				})
    69  			})
    70  		})
    71  	})
    72  }