Exemplo n.º 1
0
func (fa *FakeAuth) Login(rietveldURL string, after time.Time) error {
	fa.callLog = append(fa.callLog, "Login", rietveldURL)
	if !after.Equal(fixedSignTime) {
		return fmt.Errorf("FakeAuth: want fixedSignTime, got %v", after)
	}
	return nil
}
Exemplo n.º 2
0
// calculateMovingAverageTxDates determines the buy and sell dates for a unit based on moving average crossovers
// it returns the buyDates and the sellDates
func calculateMovingAverageTxDates(fastAvgPeriod int, slowAvgPeriod int, firstAllowedBuyDate time.Time, pricesPtr *[]metric.Metric) (*[]time.Time, *[]time.Time) {

	fastAvg := analyser.MovingAverage(fastAvgPeriod, pricesPtr)
	slowAvg := analyser.MovingAverage(slowAvgPeriod, pricesPtr)

	// Make the avgs start on the same date
	fastAvg = fastAvg[slowAvgPeriod-fastAvgPeriod:]

	// Work out the buy and sell dates
	buy := make([]time.Time, 0)
	sell := make([]time.Time, 0)

	for i := 1; i < len(fastAvg); i++ {

		if fastAvg[i].Value > slowAvg[i].Value &&
			fastAvg[i-1].Value < slowAvg[i-1].Value &&
			(firstAllowedBuyDate.Before(fastAvg[i].Time) || firstAllowedBuyDate.Equal(fastAvg[i].Time)) {
			// Low to high crossover - buy
			buy = append(buy, fastAvg[i].Time)

		} else if fastAvg[i].Value < slowAvg[i].Value && fastAvg[i-1].Value > slowAvg[i-1].Value && len(buy) > 0 {
			// High to low crossover - sell, can only sell if we've previously bought
			sell = append(sell, fastAvg[i].Time)
		}
	}

	return &buy, &sell
}
Exemplo n.º 3
0
Arquivo: rra.go Projeto: tgres/tgres
// Begins returns the timestamp of the beginning of this RRA assuming
// that that the argument "now" is within it. This will be a time
// approximately but not exactly the RRA length ago, because it is
// aligned on the RRA step boundary.
func (rra *RoundRobinArchive) Begins(now time.Time) time.Time {
	rraStart := now.Add(rra.step * time.Duration(rra.size) * -1).Truncate(rra.step)
	if now.Equal(now.Truncate(rra.step)) {
		rraStart = rraStart.Add(rra.step)
	}
	return rraStart
}
Exemplo n.º 4
0
func (s *RethinkSuite) TestTimeISO8601(c *test.C) {
	var t1, t2 time.Time
	t2, _ = time.Parse("2006-01-02T15:04:05-07:00", "1986-11-03T08:30:00-07:00")
	err := ISO8601("1986-11-03T08:30:00-07:00").RunRow(sess).Scan(&t1)
	c.Assert(err, test.IsNil)
	c.Assert(t1.Equal(t2), test.Equals, true)
}
Exemplo n.º 5
0
// isKeyValidAt returns whether the account key is valid at 'when' time.
func (ak *AccountKey) isKeyValidAt(when time.Time) bool {
	valid := when.After(ak.since) || when.Equal(ak.since)
	if valid && !ak.until.IsZero() {
		valid = when.Before(ak.until)
	}
	return valid
}
Exemplo n.º 6
0
func TestMock(t *testing.T) {
	example := mockResult(1, "int", "str", "bool", "float", "time")
	example.Next()

	var num int64
	var str string
	var boolean bool
	var float float64
	var timestamp time.Time

	example.Scanner.Scan(&num, &str, &boolean, &float, &timestamp)

	if num != mockInt {
		t.Errorf("Unequal mock int: have %d, want %d", num, mockInt)
	}
	if str != mockStr {
		t.Errorf("Unequal mock str: have %s, want %s", str, mockStr)
	}
	if boolean != mockBool {
		t.Errorf("Unequal mock bool: have %t, want %t", boolean, mockBool)
	}
	if float != mockFloat {
		t.Errorf("Unequal mock float: have %f, want %f", float, mockFloat)
	}
	if !timestamp.Equal(mockTime) {
		t.Errorf("Unequal mock time: have %v, want %v", timestamp, mockTime)
	}
}
Exemplo n.º 7
0
func TestParse(t *testing.T) {
	var (
		s    string
		p, x time.Time
		err  error
	)

	// Local time
	now := time.Now()

	times := map[string]time.Time{
		"5m":     now.Add(time.Duration(time.Minute * 5)),
		"-0h":    now.Add(-time.Duration(time.Hour * 0)),
		"-48h5m": now.Add(-time.Duration(time.Hour*48 + time.Minute*5)),

		// UTC
		"2013-04-10":                     time.Date(2013, 4, 10, 0, 0, 0, 0, time.UTC),
		"April 4, 2013":                  time.Date(2013, 4, 4, 0, 0, 0, 0, time.UTC),
		"Apr 04, 2013":                   time.Date(2013, 4, 4, 0, 0, 0, 0, time.UTC),
		"47065363200000000":              time.Date(1492, 6, 11, 0, 0, 0, 0, time.UTC),
		"02-01-2006":                     time.Date(2006, 1, 2, 0, 0, 0, 0, time.UTC),
		"02-01-2006 2:04 PM":             time.Date(2006, 1, 2, 14, 4, 0, 0, time.UTC),
		"02-01-2006 2:04 PM -0700":       time.Date(2006, 1, 2, 21, 4, 0, 0, time.UTC),
		"02-01-2006 2:04 PM -07:00":      time.Date(2006, 1, 2, 21, 4, 0, 0, time.UTC),
		"2 January 2006":                 time.Date(2006, 1, 2, 0, 0, 0, 0, time.UTC),
		"2 January 2006 3:04 PM":         time.Date(2006, 1, 2, 15, 4, 0, 0, time.UTC),
		"2 January 2006 3:04 PM -0700":   time.Date(2006, 1, 2, 22, 4, 0, 0, time.UTC),
		"2 January 2006 3:04 PM -07:00":  time.Date(2006, 1, 2, 22, 4, 0, 0, time.UTC),
		"2006-01-02":                     time.Date(2006, 1, 2, 0, 0, 0, 0, time.UTC),
		"2006-01-02 3:04 PM":             time.Date(2006, 1, 2, 15, 4, 0, 0, time.UTC),
		"2006-01-02 3:04 PM -0700":       time.Date(2006, 1, 2, 22, 4, 0, 0, time.UTC),
		"2006-01-02 3:04 PM -07:00":      time.Date(2006, 1, 2, 22, 4, 0, 0, time.UTC),
		"January 2, 2006":                time.Date(2006, 1, 2, 0, 0, 0, 0, time.UTC),
		"January 2, 2006 3:04 PM":        time.Date(2006, 1, 2, 15, 4, 0, 0, time.UTC),
		"January 2, 2006 3:04 PM -0700":  time.Date(2006, 1, 2, 22, 4, 0, 0, time.UTC),
		"January 2, 2006 3:04 PM -07:00": time.Date(2006, 1, 2, 22, 4, 0, 0, time.UTC),
		"Jan 2, 2006":                    time.Date(2006, 1, 2, 0, 0, 0, 0, time.UTC),
		"Jan 2, 2006, 3:04 PM":           time.Date(2006, 1, 2, 15, 4, 0, 0, time.UTC),
		"Jan 2, 2006 3:04 PM -0700":      time.Date(2006, 1, 2, 22, 4, 0, 0, time.UTC),
		"Jan 2, 2006 3:04 PM -07:00":     time.Date(2006, 1, 2, 22, 4, 0, 0, time.UTC),
	}

	// Duration to truncate for comparison.
	td := time.Second

	for s, x = range times {
		p, err = Parse(s)

		if err != nil {
			t.Errorf("time: failed to parse %s as time", s)
		} else {
			x = x.Truncate(td)
			p = p.Truncate(td)

			if !p.Equal(x) {
				t.Errorf("time: expected %s, got %s", x, p)
			}
		}
	}
}
Exemplo n.º 8
0
func isStartOfMonth(t time.Time) bool {
	y := t.Year()
	m := t.Month()
	utcLoc, _ := time.LoadLocation("UTC")
	startOfMonth := time.Date(y, m, 1, 0, 0, 0, 0, utcLoc)
	return t.Equal(startOfMonth)
}
Exemplo n.º 9
0
func LoadPerf(fName string, since, until time.Time) ([]PerfLogEntry, error) {
	fIn, err := os.Open(fName)
	if err != nil {
		return nil, err
	}
	defer fIn.Close()

	dec := json.NewDecoder(fIn)
	var result []PerfLogEntry
	for {
		var entry PerfLogEntry
		err = dec.Decode(&entry)
		if err != nil {
			if strings.Contains(err.Error(), "EOF") {
				break
			} else {
				return nil, fmt.Errorf("Decode error: %v", err)
			}
		} else {
			if !since.Equal(time.Time{}) && since.After(entry.Timestamp) {
				continue
			}
			if !until.Equal(time.Time{}) && until.Before(entry.Timestamp) {
				continue
			}
			result = append(result, entry)
		}
	}
	return result, nil
}
Exemplo n.º 10
0
func in(date, start, end time.Time) bool {
	if date.Equal(start) || date.Equal(end) {
		return true
	}

	return date.After(start) && date.Before(end)
}
Exemplo n.º 11
0
func (r *VirtualMtimeRepo) GetMtime(path string, diskMtime time.Time) time.Time {
	data, exists := r.ns.Bytes(path)
	if !exists {
		// Absense of debug print is significant enough in itself here
		return diskMtime
	}

	var mtime time.Time
	if err := mtime.UnmarshalBinary(data[:len(data)/2]); err != nil {
		panic(fmt.Sprintf("Can't unmarshal stored mtime at path %s: %v", path, err))
	}

	if mtime.Equal(diskMtime) {
		if err := mtime.UnmarshalBinary(data[len(data)/2:]); err != nil {
			panic(fmt.Sprintf("Can't unmarshal stored mtime at path %s: %v", path, err))
		}

		if debug {
			l.Debugf("virtual mtime: return %v instead of %v for path: %s", mtime, diskMtime, path)
		}
		return mtime
	}

	if debug {
		l.Debugf("virtual mtime: record exists, but mismatch inDisk: %v dbDisk: %v for path: %s", diskMtime, mtime, path)
	}
	return diskMtime
}
Exemplo n.º 12
0
Arquivo: ds.go Projeto: tgres/tgres
// surroundingStep returns begin and end of a PDP which either
// includes or ends on a given time mark.
func surroundingStep(mark time.Time, step time.Duration) (time.Time, time.Time) {
	begin := mark.Truncate(step)
	if mark.Equal(begin) { // We are exactly at the end, need to move one step back.
		begin = begin.Add(step * -1)
	}
	return begin, begin.Add(step)
}
Exemplo n.º 13
0
func ftime2Func(t time.Time) string {
	if t == zeroTime || t.Equal(walker.NotYetCrawled) {
		return ""
	} else {
		return t.Format(timeFormat)
	}
}
Exemplo n.º 14
0
func assertExpectedTUFMetaInStore(t *testing.T, s MetaStore, expected []StoredTUFMeta, current bool) {
	for _, tufObj := range expected {
		var prevTime *time.Time
		if current {
			cDate, tufdata, err := s.GetCurrent(tufObj.Gun, tufObj.Role)
			require.NoError(t, err)
			require.Equal(t, tufObj.Data, tufdata)

			// the update date was sometime wthin the last minute
			require.True(t, cDate.After(time.Now().Add(-1*time.Minute)))
			require.True(t, cDate.Before(time.Now().Add(5*time.Second)))
			prevTime = cDate
		}

		checksumBytes := sha256.Sum256(tufObj.Data)
		checksum := hex.EncodeToString(checksumBytes[:])

		cDate, tufdata, err := s.GetChecksum(tufObj.Gun, tufObj.Role, checksum)
		require.NoError(t, err)
		require.Equal(t, tufObj.Data, tufdata)

		if current {
			require.True(t, prevTime.Equal(*cDate), "%s should be equal to %s", prevTime, cDate)
		} else {
			// the update date was sometime wthin the last minute
			require.True(t, cDate.After(time.Now().Add(-1*time.Minute)))
			require.True(t, cDate.Before(time.Now().Add(5*time.Second)))
		}
	}
}
Exemplo n.º 15
0
// ValidAt returns whether the system-user is valid at 'when' time.
func (su *SystemUser) ValidAt(when time.Time) bool {
	valid := when.After(su.since) || when.Equal(su.since)
	if valid {
		valid = when.Before(su.until)
	}
	return valid
}
Exemplo n.º 16
0
// tryUpdate tries to update conf with the named resolv.conf file.
// The name variable only exists for testing. It is otherwise always
// "/etc/resolv.conf".
func (conf *resolverConfig) tryUpdate(name string) {
	conf.initOnce.Do(conf.init)

	// Ensure only one update at a time checks resolv.conf.
	if !conf.tryAcquireSema() {
		return
	}
	defer conf.releaseSema()

	now := time.Now()
	if conf.lastChecked.After(now.Add(-5 * time.Second)) {
		return
	}
	conf.lastChecked = now

	var mtime time.Time
	if fi, err := os.Stat(name); err == nil {
		mtime = fi.ModTime()
	}
	if mtime.Equal(conf.dnsConfig.mtime) {
		return
	}

	dnsConf := dnsReadConfig(name)
	conf.mu.Lock()
	conf.dnsConfig = dnsConf
	conf.mu.Unlock()
}
Exemplo n.º 17
0
func (gp *GoPdf) bindInfo(buff *bytes.Buffer) {
	var zerotime time.Time
	buff.WriteString("/Info <<\n")

	if gp.info.Author != "" {
		buff.WriteString(fmt.Sprintf("/Author <FEFF%s>\n", encodeUtf8(gp.info.Author)))
	}

	if gp.info.Title != "" {
		buff.WriteString(fmt.Sprintf("/Title <FEFF%s>\n", encodeUtf8(gp.info.Title)))
	}

	if gp.info.Subject != "" {
		buff.WriteString(fmt.Sprintf("/Subject <FEFF%s>\n", encodeUtf8(gp.info.Subject)))
	}

	if gp.info.Creator != "" {
		buff.WriteString(fmt.Sprintf("/Creator <FEFF%s>\n", encodeUtf8(gp.info.Creator)))
	}

	if gp.info.Producer != "" {
		buff.WriteString(fmt.Sprintf("/Producer <FEFF%s>\n", encodeUtf8(gp.info.Producer)))
	}

	if !zerotime.Equal(gp.info.CreationDate) {
		buff.WriteString(fmt.Sprintf("/CreationDate(D:%s)>>\n", infodate(gp.info.CreationDate)))
	}

	buff.WriteString(" >>\n")
}
Exemplo n.º 18
0
func TestSetGetChecked(t *testing.T) {
	v := Value{}

	v.SetBytes(nil)
	if _, err := v.GetBytes(); err != nil {
		t.Fatal(err)
	}

	f := 1.1
	v.SetFloat(f)
	if r, err := v.GetFloat(); err != nil {
		t.Fatal(err)
	} else if f != r {
		t.Errorf("set %f on a value and extracted it, expected %f back, but got %f", f, f, r)
	}

	i := int64(1)
	v.SetInt(i)
	if r, err := v.GetInt(); err != nil {
		t.Fatal(err)
	} else if i != r {
		t.Errorf("set %d on a value and extracted it, expected %d back, but got %d", i, i, r)
	}

	dec := inf.NewDec(11, 1)
	if err := v.SetDecimal(dec); err != nil {
		t.Fatal(err)
	}
	if r, err := v.GetDecimal(); err != nil {
		t.Fatal(err)
	} else if dec.Cmp(r) != 0 {
		t.Errorf("set %s on a value and extracted it, expected %s back, but got %s", dec, dec, r)
	}

	if err := v.SetProto(&Value{}); err != nil {
		t.Fatal(err)
	}
	if err := v.GetProto(&Value{}); err != nil {
		t.Fatal(err)
	}
	if _, err := v.GetBytes(); err != nil {
		t.Fatal(err)
	}

	if err := v.SetProto(&InternalTimeSeriesData{}); err != nil {
		t.Fatal(err)
	}
	if _, err := v.GetTimeseries(); err != nil {
		t.Fatal(err)
	}

	ti := time.Time{}
	v.SetTime(ti)
	if r, err := v.GetTime(); err != nil {
		t.Fatal(err)
	} else if !ti.Equal(r) {
		t.Errorf("set %s on a value and extracted it, expected %s back, but got %s", ti, ti, r)
	}
}
Exemplo n.º 19
0
// updateTime updates the Cluster timestamp to the specified time.
func (rc *realCluster) updateTime(new_time time.Time) {
	if new_time.Equal(time.Time{}) {
		return
	}
	rc.lock.Lock()
	defer rc.lock.Unlock()
	rc.timestamp = new_time
}
Exemplo n.º 20
0
func isAfterMin(minTime time.Time, lastLagerTime time.Time) bool {
	if minTime.IsZero() {
		return true
	}
	if lastLagerTime.IsZero() {
		return false
	}
	return lastLagerTime.After(minTime) || lastLagerTime.Equal(minTime)
}
Exemplo n.º 21
0
func TestRDBPrivateKeyJSONUnmarshalling(t *testing.T) {
	created := time.Now().AddDate(-1, -1, -1)
	updated := time.Now().AddDate(0, -5, 0)
	deleted := time.Time{}
	publicKey := []byte("Hello world public")
	privateKey := []byte("Hello world private")

	createdMarshalled, err := json.Marshal(created)
	require.NoError(t, err)
	updatedMarshalled, err := json.Marshal(updated)
	require.NoError(t, err)
	deletedMarshalled, err := json.Marshal(deleted)
	require.NoError(t, err)
	publicMarshalled, err := json.Marshal(publicKey)
	require.NoError(t, err)
	privateMarshalled, err := json.Marshal(privateKey)
	require.NoError(t, err)

	jsonBytes := []byte(fmt.Sprintf(`
	{
		"created_at": %s,
		"updated_at": %s,
		"deleted_at": %s,
		"key_id": "56ee4a23129fc22c6cb4b4ba5f78d730c91ab6def514e80d807c947bb21f0d63",
		"encryption_alg": "A256GCM",
		"keywrap_alg": "PBES2-HS256+A128KW",
		"algorithm": "ecdsa",
		"passphrase_alias": "timestamp_1",
		"public": %s,
		"private": %s
	}
	`, createdMarshalled, updatedMarshalled, deletedMarshalled, publicMarshalled, privateMarshalled))

	unmarshalledAnon, err := PrivateKeysRethinkTable.JSONUnmarshaller(jsonBytes)
	require.NoError(t, err)
	unmarshalled, ok := unmarshalledAnon.(RDBPrivateKey)
	require.True(t, ok)

	// There is some weirdness with comparing time.Time due to a location pointer,
	// so let's use time.Time's equal function to compare times, and then re-assign
	// the timing struct to compare the rest of the RDBTUFFile struct
	require.True(t, created.Equal(unmarshalled.CreatedAt))
	require.True(t, updated.Equal(unmarshalled.UpdatedAt))
	require.True(t, deleted.Equal(unmarshalled.DeletedAt))

	expected := RDBPrivateKey{
		Timing:          unmarshalled.Timing,
		KeyID:           "56ee4a23129fc22c6cb4b4ba5f78d730c91ab6def514e80d807c947bb21f0d63",
		EncryptionAlg:   "A256GCM",
		KeywrapAlg:      "PBES2-HS256+A128KW",
		Algorithm:       "ecdsa",
		PassphraseAlias: "timestamp_1",
		Public:          publicKey,
		Private:         privateKey,
	}
	require.Equal(t, expected, unmarshalled)
}
Exemplo n.º 22
0
func (i *Datetime) withinBounds(t time.Time) bool {
	if t.Equal(i.Start) {
		return true
	}
	if t.After(i.Start) && t.Before(i.End) {
		return true
	}
	return false
}
Exemplo n.º 23
0
func (s *RethinkSuite) TestTimeTimeMillisecond(c *test.C) {
	var response time.Time
	res, err := Time(1986, 11, 3, 12, 30, 15.679, "Z").Run(sess)
	c.Assert(err, test.IsNil)

	err = res.One(&response)
	c.Assert(err, test.IsNil)
	c.Assert(response.Equal(time.Date(1986, 11, 3, 12, 30, 15, 679.00002*1000*1000, time.UTC)), test.Equals, true)
}
Exemplo n.º 24
0
func (s *RethinkSuite) TestTimeEpochTime(c *test.C) {
	var response time.Time
	res, err := EpochTime(531360000).Run(session)
	c.Assert(err, test.IsNil)

	err = res.One(&response)
	c.Assert(err, test.IsNil)
	c.Assert(response.Equal(time.Date(1986, 11, 3, 0, 0, 0, 0, time.UTC)), test.Equals, true)
}
Exemplo n.º 25
0
func (s *RethinkSuite) TestTimeTime(c *test.C) {
	var response time.Time
	res, err := Time(1986, 11, 3, 12, 30, 15, "Z").Run(session)
	c.Assert(err, test.IsNil)

	err = res.One(&response)
	c.Assert(err, test.IsNil)
	c.Assert(response.Equal(time.Date(1986, 11, 3, 12, 30, 15, 0, time.UTC)), test.Equals, true)
}
Exemplo n.º 26
0
func isBeforeMax(maxTime time.Time, lastLagerTime time.Time) bool {
	if maxTime.IsZero() {
		return true
	}
	if lastLagerTime.IsZero() {
		return true
	}
	return lastLagerTime.Before(maxTime) || lastLagerTime.Equal(maxTime)
}
Exemplo n.º 27
0
func renderDate(t time.Time) string {
	// TODO(sadovsky): For now, we always use Pacific time.
	loc, err := time.LoadLocation("America/Los_Angeles")
	CheckError(err)
	if t.Equal(time.Unix(0, 0)) {
		loc = time.UTC
	}
	// return t.In(loc).Format("Jan 2 15:04:05")
	return t.In(loc).Format("Jan 2")
}
Exemplo n.º 28
0
func (a *Assert) EqTime(expect, got time.Time, msg string, params ...interface{}) *Assert {
	if !expect.Equal(got) {
		_, file, line, _ := runtime.Caller(1)
		file = filepath.Base(file)
		sexpect, _ := expect.MarshalJSON()
		sgot, _ := got.MarshalJSON()
		a.t.Fatalf("Assert.EqTime failure <%s:%d>: (expect: %s, got:%s): %q", file, line, sexpect, sgot, fmt.Sprintf(msg, params...))
	}
	return a
}
Exemplo n.º 29
0
func insertNum(t *testing.T, conn *sql.Tx,
	small int, bigint string,
	notint float64, bigreal string,
	text string, date time.Time,
) bool {
	date = date.Round(time.Second)
	qry := fmt.Sprintf(`INSERT INTO `+tbl+`
			(F_int, F_bigint, F_real, F_bigreal, F_text, F_date)
			VALUES (%d, %s, %3.3f, %s, '%s', TO_DATE('%s', 'YYYY-MM-DD HH24:MI:SS'))
			`, small, bigint, notint, bigreal, text, date.Format("2006-01-02 15:04:05"))
	if _, err := conn.Exec(qry); err != nil {
		t.Errorf("cannot insert into "+tbl+" (%q): %v", qry, err)
		return false
	}
	row := conn.QueryRow("SELECT F_int, F_bigint, F_real, F_bigreal, F_text, F_date FROM "+tbl+" WHERE F_int = :1", small)
	var (
		smallO             int
		bigintO            big.Int
		notintO            float64
		bigrealF, bigrealO big.Rat
		bigintS, bigrealS  string
		textO              string
		dateO              time.Time
	)
	if err := row.Scan(&smallO, &bigintS, &notintO, &bigrealS, &textO, &dateO); err != nil {
		t.Errorf("error scanning row[%d]: %v", small, errgo.Details(err))
		return false
	}
	t.Logf("row: small=%d big=%s notint=%f bigreal=%s text=%q date=%s",
		smallO, bigintS, notintO, bigrealS, textO, dateO)

	if smallO != small {
		t.Errorf("small mismatch: got %d, awaited %d.", smallO, small)
	}
	(&bigintO).SetString(bigintS, 10)
	if bigintO.String() != bigint {
		t.Errorf("bigint mismatch: got %s, awaited %s.", bigintO, bigint)
	}
	if notintO != notint {
		t.Errorf("noting mismatch: got %f, awaited %f.", notintO, notint)
	}
	(&bigrealF).SetString(bigreal)
	(&bigrealO).SetString(bigrealS)
	if (&bigrealO).Cmp(&bigrealF) != 0 {
		t.Errorf("bigreal mismatch: got %s, awaited %f.", (&bigrealO), (&bigrealF))
	}
	if textO != text {
		t.Errorf("text mismatch: got %q, awaited %q.", textO, text)
	}
	if !dateO.Equal(date) {
		t.Errorf("date mismatch: got %s, awaited %s.", dateO, date.Round(time.Second))
	}

	return true
}
Exemplo n.º 30
0
func TestRDBTUFFileJSONUnmarshalling(t *testing.T) {
	created := time.Now().AddDate(-1, -1, -1)
	updated := time.Now().AddDate(0, -5, 0)
	deleted := time.Time{}
	data := []byte("Hello world")

	createdMarshalled, err := json.Marshal(created)
	require.NoError(t, err)
	updatedMarshalled, err := json.Marshal(updated)
	require.NoError(t, err)
	deletedMarshalled, err := json.Marshal(deleted)
	require.NoError(t, err)
	dataMarshalled, err := json.Marshal(data)
	require.NoError(t, err)

	jsonBytes := []byte(fmt.Sprintf(`
	{
		"created_at": %s,
		"updated_at": %s,
		"deleted_at": %s,
		"gun_role_version": ["completely", "invalid", "garbage"],
		"gun": "namespaced/name",
		"role": "timestamp",
		"version": 5,
		"sha256": "56ee4a23129fc22c6cb4b4ba5f78d730c91ab6def514e80d807c947bb21f0d63",
		"data": %s,
		"timestamp_checksum": "ebe6b6e082c94ef24043f1786a7046432506c3d193a47c299ed48ff4413ad7b0"
	}
	`, createdMarshalled, updatedMarshalled, deletedMarshalled, dataMarshalled))

	unmarshalledAnon, err := TUFFilesRethinkTable.JSONUnmarshaller(jsonBytes)
	require.NoError(t, err)
	unmarshalled, ok := unmarshalledAnon.(RDBTUFFile)
	require.True(t, ok)

	// There is some weirdness with comparing time.Time due to a location pointer,
	// so let's use time.Time's equal function to compare times, and then re-assign
	// the timing struct to compare the rest of the RDBTUFFile struct
	require.True(t, created.Equal(unmarshalled.CreatedAt))
	require.True(t, updated.Equal(unmarshalled.UpdatedAt))
	require.True(t, deleted.Equal(unmarshalled.DeletedAt))

	expected := RDBTUFFile{
		Timing:         unmarshalled.Timing,
		GunRoleVersion: []interface{}{"namespaced/name", "timestamp", 5},
		Gun:            "namespaced/name",
		Role:           "timestamp",
		Version:        5,
		Sha256:         "56ee4a23129fc22c6cb4b4ba5f78d730c91ab6def514e80d807c947bb21f0d63",
		Data:           data,
		TSchecksum:     "ebe6b6e082c94ef24043f1786a7046432506c3d193a47c299ed48ff4413ad7b0",
	}
	require.Equal(t, expected, unmarshalled)
}