示例#1
1
func TestFileStore_Read(t *testing.T) {
	fs := tsm1.NewFileStore("")

	// Setup 3 files
	data := []keyValues{
		keyValues{"cpu", []tsm1.Value{tsm1.NewValue(time.Unix(0, 0), 1.0)}},
		keyValues{"cpu", []tsm1.Value{tsm1.NewValue(time.Unix(1, 0), 2.0)}},
		keyValues{"mem", []tsm1.Value{tsm1.NewValue(time.Unix(0, 0), 1.0)}},
	}

	files, err := newFiles(data...)
	if err != nil {
		t.Fatalf("unexpected error creating files: %v", err)
	}

	fs.Add(files...)

	// Search for an entry that exists in the second file
	values, err := fs.Read("cpu", time.Unix(1, 0))
	if err != nil {
		t.Fatalf("unexpected error reading values: %v", err)
	}

	exp := data[1]
	if got, exp := len(values), len(exp.values); got != exp {
		t.Fatalf("value length mismatch: got %v, exp %v", got, exp)
	}

	for i, v := range exp.values {
		if got, exp := values[i].Value(), v.Value(); got != exp {
			t.Fatalf("read value mismatch(%d): got %v, exp %d", i, got, exp)
		}
	}
}
示例#2
1
func XXXTestBulkErrors(t *testing.T) {
	// lets set a bad port, and hope we get a conn refused error?
	c := NewTestConn()
	c.Port = "27845"
	defer func() {
		c.Port = "9200"
	}()
	indexer := c.NewBulkIndexerErrors(10, 1)
	indexer.Start()
	errorCt := 0
	go func() {
		for i := 0; i < 20; i++ {
			date := time.Unix(1257894000, 0)
			data := map[string]interface{}{"name": "smurfs", "age": 22, "date": time.Unix(1257894000, 0)}
			indexer.Index("users", "user", strconv.Itoa(i), "", &date, data, true)
		}
	}()
	var errBuf *ErrorBuffer
	for errBuf = range indexer.ErrorChannel {
		errorCt++
		break
	}
	if errBuf.Buf.Len() > 0 {
		gou.Debug(errBuf.Err)
	}
	assert.T(t, errorCt > 0, fmt.Sprintf("ErrorCt should be > 0 %d", errorCt))
	indexer.Stop()
}
示例#3
1
func TestAction(t *testing.T) {

	action := NewAction(false, "Something")
	action.End = now + 20

	Convey("Get right start date", t, func() {
		expectedStart := time.Unix(now, 0).Format(DateFormat)
		So(action.GetStartDate(), ShouldEqual, expectedStart)
	})
	Convey("Get right end date", t, func() {
		expectedEnd := time.Unix(now+20, 0).Format(DateFormat)
		So(action.GetEndDate(), ShouldEqual, expectedEnd)
	})
	Convey("Get end date for a process which is not finished", t, func() {
		action.End = 0
		So(action.GetEndDate(), ShouldEqual, "Not yet")
	})
	Convey("right result", t, func() {
		action.ChangeResult("danger")
		So(action.GetResult(), ShouldEqual, "danger")
	})
	Convey("Complete example", t, func() {
		action2 := &Action{
			Start: now,
			End:   0,
		}
		So(action.GetEndDate(), ShouldEqual, "Not yet")

		action2.ChangeResult("warning")
		action2.Finish()
		So(action.IsRunning, ShouldBeFalse)
	})
}
示例#4
0
文件: x509_test.go 项目: Ericean/go
func TestCRLCreation(t *testing.T) {
	block, _ := pem.Decode([]byte(pemPrivateKey))
	priv, _ := ParsePKCS1PrivateKey(block.Bytes)
	block, _ = pem.Decode([]byte(pemCertificate))
	cert, _ := ParseCertificate(block.Bytes)

	now := time.Unix(1000, 0)
	expiry := time.Unix(10000, 0)

	revokedCerts := []pkix.RevokedCertificate{
		{
			SerialNumber:   big.NewInt(1),
			RevocationTime: now,
		},
		{
			SerialNumber:   big.NewInt(42),
			RevocationTime: now,
		},
	}

	crlBytes, err := cert.CreateCRL(rand.Reader, priv, revokedCerts, now, expiry)
	if err != nil {
		t.Errorf("error creating CRL: %s", err)
	}

	_, err = ParseDERCRL(crlBytes)
	if err != nil {
		t.Errorf("error reparsing CRL: %s", err)
	}
}
示例#5
0
func (self *ClusterConfiguration) getStartAndEndBasedOnDuration(microsecondsEpoch int64, duration float64) (*time.Time, *time.Time) {
	startTimeSeconds := math.Floor(float64(microsecondsEpoch)/1000.0/1000.0/duration) * duration
	startTime := time.Unix(int64(startTimeSeconds), 0)
	endTime := time.Unix(int64(startTimeSeconds+duration), 0)

	return &startTime, &endTime
}
示例#6
0
// GetFirstTimestamp returns the timestamp of the first packet
func GetFirstTimestamp(filepath string) (*time.Time, error) {
	data, err := readHeaders(filepath)
	if err != nil {
		return nil, err
	}
	typ, e, err := isPcap(data)
	if err != nil {
		return nil, err
	} else if typ == INVALID || typ == PCAP_NG {
		return nil, errors.New("not a valid pcap")
	}

	if len(data) < 24+4 {
		return nil, errors.New("no packet the in pcap")
	}

	if e == LITTLE {
		i := binary.LittleEndian.Uint32(data[24 : 24+4]) // access to ts_sec; in the first packet's heade
		t := time.Unix((int64)(i), 0)
		return &t, nil
	} else {
		i := binary.BigEndian.Uint32(data[24 : 24+4]) // access to ts_sec; in the first packet's heade
		t := time.Unix((int64)(i), 0)
		return &t, nil
	}
}
func NewRetentionPolicy(name string, duration time.Duration, nodeCount int) *meta.RetentionPolicyInfo {
	shards := []meta.ShardInfo{}
	owners := []meta.ShardOwner{}
	for i := 1; i <= nodeCount; i++ {
		owners = append(owners, meta.ShardOwner{NodeID: uint64(i)})
	}

	// each node is fully replicated with each other
	shards = append(shards, meta.ShardInfo{
		ID:     nextShardID(),
		Owners: owners,
	})

	rp := &meta.RetentionPolicyInfo{
		Name:               "myrp",
		ReplicaN:           nodeCount,
		Duration:           duration,
		ShardGroupDuration: duration,
		ShardGroups: []meta.ShardGroupInfo{
			meta.ShardGroupInfo{
				ID:        nextShardID(),
				StartTime: time.Unix(0, 0),
				EndTime:   time.Unix(0, 0).Add(duration).Add(-1),
				Shards:    shards,
			},
		},
	}
	return rp
}
示例#8
0
func TestParsePointEscapedStringsAndCommas(t *testing.T) {
	// non-escaped comma and quotes
	test(t, `cpu,host=serverA,region=us-east value="{Hello\"{,}\" World}" 1000000000`,
		tsdb.NewPoint(
			"cpu",
			tsdb.Tags{
				"host":   "serverA",
				"region": "us-east",
			},
			tsdb.Fields{
				"value": `{Hello"{,}" World}`,
			},
			time.Unix(1, 0)),
	)

	// escaped comma and quotes
	test(t, `cpu,host=serverA,region=us-east value="{Hello\"{\,}\" World}" 1000000000`,
		tsdb.NewPoint(
			"cpu",
			tsdb.Tags{
				"host":   "serverA",
				"region": "us-east",
			},
			tsdb.Fields{
				"value": `{Hello"{\,}" World}`,
			},
			time.Unix(1, 0)),
	)
}
示例#9
0
func TestNewPointNaN(t *testing.T) {
	test(t, `cpu value=NaN 1000000000`,
		tsdb.NewPoint(
			"cpu",
			tsdb.Tags{},
			tsdb.Fields{
				"value": math.NaN(),
			},
			time.Unix(1, 0)),
	)

	test(t, `cpu value=nAn 1000000000`,
		tsdb.NewPoint(
			"cpu",
			tsdb.Tags{},
			tsdb.Fields{
				"value": math.NaN(),
			},
			time.Unix(1, 0)),
	)

	test(t, `nan value=NaN`,
		tsdb.NewPoint(
			"nan",
			tsdb.Tags{},
			tsdb.Fields{
				"value": math.NaN(),
			},
			time.Unix(0, 0)),
	)

}
示例#10
0
func TestParsePointWithStringField(t *testing.T) {
	test(t, `cpu,host=serverA,region=us-east value=1.0,str="foo",str2="bar" 1000000000`,
		tsdb.NewPoint("cpu",
			tsdb.Tags{
				"host":   "serverA",
				"region": "us-east",
			},
			tsdb.Fields{
				"value": 1.0,
				"str":   "foo",
				"str2":  "bar",
			},
			time.Unix(1, 0)),
	)

	test(t, `cpu,host=serverA,region=us-east str="foo \" bar" 1000000000`,
		tsdb.NewPoint("cpu",
			tsdb.Tags{
				"host":   "serverA",
				"region": "us-east",
			},
			tsdb.Fields{
				"str": `foo " bar`,
			},
			time.Unix(1, 0)),
	)

}
示例#11
0
func TestParsePointWithStringWithCommas(t *testing.T) {
	// escaped comma
	test(t, `cpu,host=serverA,region=us-east value=1.0,str="foo\,bar" 1000000000`,
		tsdb.NewPoint(
			"cpu",
			tsdb.Tags{
				"host":   "serverA",
				"region": "us-east",
			},
			tsdb.Fields{
				"value": 1.0,
				"str":   `foo\,bar`, // commas in string value
			},
			time.Unix(1, 0)),
	)

	// non-escaped comma
	test(t, `cpu,host=serverA,region=us-east value=1.0,str="foo,bar" 1000000000`,
		tsdb.NewPoint(
			"cpu",
			tsdb.Tags{
				"host":   "serverA",
				"region": "us-east",
			},
			tsdb.Fields{
				"value": 1.0,
				"str":   "foo,bar", // commas in string value
			},
			time.Unix(1, 0)),
	)
}
示例#12
0
// Parese network's "addr" message
func ParseAddr(pl []byte) {
	b := bytes.NewBuffer(pl)
	cnt, _ := btc.ReadVLen(b)
	for i := 0; i < int(cnt); i++ {
		var buf [30]byte
		n, e := b.Read(buf[:])
		if n != len(buf) || e != nil {
			common.CountSafe("AddrError")
			//println("ParseAddr:", n, e)
			break
		}
		a := NewPeer(buf[:])
		if !ValidIp4(a.Ip4[:]) {
			common.CountSafe("AddrInvalid")
		} else if time.Unix(int64(a.Time), 0).Before(time.Now().Add(time.Minute)) {
			if time.Now().Before(time.Unix(int64(a.Time), 0).Add(ExpirePeerAfter)) {
				k := qdb.KeyType(a.UniqID())
				v := PeerDB.Get(k)
				if v != nil {
					a.Banned = NewPeer(v[:]).Banned
				}
				PeerDB.Put(k, a.Bytes())
			} else {
				common.CountSafe("AddrStale")
			}
		} else {
			common.CountSafe("AddrInFuture")
		}
	}
}
示例#13
0
func TestFileStore_Open(t *testing.T) {
	dir := MustTempDir()
	defer os.RemoveAll(dir)

	// Create 3 TSM files...
	data := []keyValues{
		keyValues{"cpu", []tsm1.Value{tsm1.NewValue(time.Unix(0, 0), 1.0)}},
		keyValues{"cpu", []tsm1.Value{tsm1.NewValue(time.Unix(1, 0), 2.0)}},
		keyValues{"mem", []tsm1.Value{tsm1.NewValue(time.Unix(0, 0), 1.0)}},
	}

	_, err := newFileDir(dir, data...)
	if err != nil {
		fatal(t, "creating test files", err)
	}

	fs := tsm1.NewFileStore(dir)
	if err := fs.Open(); err != nil {
		fatal(t, "opening file store", err)
	}
	defer fs.Close()

	if got, exp := fs.Count(), 3; got != exp {
		t.Fatalf("file count mismatch: got %v, exp %v", got, exp)
	}

	if got, exp := fs.CurrentID(), 4; got != exp {
		t.Fatalf("current ID mismatch: got %v, exp %v", got, exp)
	}
}
示例#14
0
func TestFileStore_Delete(t *testing.T) {
	fs := tsm1.NewFileStore("")

	// Setup 3 files
	data := []keyValues{
		keyValues{"cpu,host=server2!~#!value", []tsm1.Value{tsm1.NewValue(time.Unix(0, 0), 1.0)}},
		keyValues{"cpu,host=server1!~#!value", []tsm1.Value{tsm1.NewValue(time.Unix(1, 0), 2.0)}},
		keyValues{"mem,host=server1!~#!value", []tsm1.Value{tsm1.NewValue(time.Unix(0, 0), 1.0)}},
	}

	files, err := newFiles(data...)
	if err != nil {
		t.Fatalf("unexpected error creating files: %v", err)
	}

	fs.Add(files...)

	keys := fs.Keys()
	if got, exp := len(keys), 3; got != exp {
		t.Fatalf("key length mismatch: got %v, exp %v", got, exp)
	}

	if err := fs.Delete("cpu,host=server2!~#!value"); err != nil {
		fatal(t, "deleting", err)
	}

	keys = fs.Keys()
	if got, exp := len(keys), 2; got != exp {
		t.Fatalf("key length mismatch: got %v, exp %v", got, exp)
	}
}
示例#15
0
// Ensure the engine can write points to storage.
func TestEngine_WritePoints_PointsWriter(t *testing.T) {
	e := OpenDefaultEngine()
	defer e.Close()

	// Points to be inserted.
	points := []models.Point{
		models.NewPoint("cpu", models.Tags{}, models.Fields{}, time.Unix(0, 1)),
		models.NewPoint("cpu", models.Tags{}, models.Fields{}, time.Unix(0, 0)),
		models.NewPoint("cpu", models.Tags{}, models.Fields{}, time.Unix(1, 0)),

		models.NewPoint("cpu", models.Tags{"host": "serverA"}, models.Fields{}, time.Unix(0, 0)),
	}

	// Mock points writer to ensure points are passed through.
	var invoked bool
	e.PointsWriter.WritePointsFn = func(a []models.Point) error {
		invoked = true
		if !reflect.DeepEqual(points, a) {
			t.Fatalf("unexpected points: %#v", a)
		}
		return nil
	}

	// Write points against two separate series.
	if err := e.WritePoints(points, nil, nil); err != nil {
		t.Fatal(err)
	} else if !invoked {
		t.Fatal("PointsWriter.WritePoints() not called")
	}
}
示例#16
0
func TestPeriodicHeap_Order(t *testing.T) {
	h := NewPeriodicHeap()
	j1 := mock.PeriodicJob()
	j2 := mock.PeriodicJob()
	j3 := mock.PeriodicJob()

	lookup := map[*structs.Job]string{
		j1: "j1",
		j2: "j2",
		j3: "j3",
	}

	h.Push(j1, time.Time{})
	h.Push(j2, time.Unix(10, 0))
	h.Push(j3, time.Unix(11, 0))

	exp := []string{"j2", "j3", "j1"}
	var act []string
	for i := 0; i < 3; i++ {
		pJob := h.Pop()
		act = append(act, lookup[pJob.job])
	}

	if !reflect.DeepEqual(act, exp) {
		t.Fatalf("Wrong ordering; got %v; want %v", act, exp)
	}
}
示例#17
0
// Given a well formed Token we should get back a well formed request.
func TestBuildRequest(t *testing.T) {
	c := &ClaimSet{
		Iss:   iss,
		Scope: scope,
		exp:   time.Unix(exp, 0),
		iat:   time.Unix(iat, 0),
	}
	tok := &Token{
		ClaimSet: c,
		Header:   stdHeader,
		Key:      privateKeyPemBytes,
	}
	u, v, err := tok.buildRequest()
	if err != nil {
		t.Errorf("TestBuildRequest:BuildRequest: %v", err)
	}
	if u != c.Aud {
		t.Error("TestBuildRequest: u != c.Aud")
		t.Errorf("      u = %s", u)
		t.Errorf("  c.Aud = %s", c.Aud)
	}
	if v.Get("grant_type") != stdGrantType {
		t.Error("TestBuildRequest: grant_type != stdGrantType")
		t.Errorf("    grant_type = %s", v.Get("grant_type"))
		t.Errorf("  stdGrantType = %s", stdGrantType)
	}
	if v.Get("assertion") != tokEnc {
		t.Error("TestBuildRequest: assertion != tokEnc")
		t.Errorf("  assertion = %s", v.Get("assertion"))
		t.Errorf("     tokEnc = %s", tokEnc)
	}
}
示例#18
0
文件: node.go 项目: guanqun/cockroach
// nodeStatusesToRows converts NodeStatuses to SQL-like result rows, so that we can pretty-print
// them.
func nodeStatusesToRows(statuses []status.NodeStatus) [][]string {
	// Create results that are like the results for SQL results, so that we can pretty-print them.
	var rows [][]string
	for _, nodeStatus := range statuses {
		hostPort := nodeStatus.Desc.Address.AddressField
		updatedAt := time.Unix(nodeStatus.UpdatedAt/1e9, nodeStatus.UpdatedAt%1e9)
		updatedAtStr := updatedAt.Format(localTimeFormat)
		startedAt := time.Unix(nodeStatus.StartedAt/1e9, nodeStatus.StartedAt%1e9)
		startedAtStr := startedAt.Format(localTimeFormat)

		rows = append(rows, []string{
			strconv.FormatInt(int64(nodeStatus.Desc.NodeID), 10),
			hostPort,
			updatedAtStr,
			startedAtStr,
			strconv.FormatInt(int64(nodeStatus.Stats.LiveBytes), 10),
			strconv.FormatInt(int64(nodeStatus.Stats.KeyBytes), 10),
			strconv.FormatInt(int64(nodeStatus.Stats.ValBytes), 10),
			strconv.FormatInt(int64(nodeStatus.Stats.IntentBytes), 10),
			strconv.FormatInt(int64(nodeStatus.Stats.SysBytes), 10),
			strconv.FormatInt(int64(nodeStatus.LeaderRangeCount), 10),
			strconv.FormatInt(int64(nodeStatus.ReplicatedRangeCount), 10),
			strconv.FormatInt(int64(nodeStatus.AvailableRangeCount), 10),
		})
	}
	return rows
}
示例#19
0
func TestDocumentStaticMapping(t *testing.T) {
	defer func() {
		err := os.RemoveAll("testidx")
		if err != nil {
			t.Fatal(err)
		}
	}()

	m := NewIndexMapping()
	m.DefaultMapping = NewDocumentStaticMapping()
	m.DefaultMapping.AddFieldMappingsAt("Text", NewTextFieldMapping())
	m.DefaultMapping.AddFieldMappingsAt("Date", NewDateTimeFieldMapping())
	m.DefaultMapping.AddFieldMappingsAt("Numeric", NewNumericFieldMapping())

	index, err := New("testidx", m)
	if err != nil {
		t.Fatal(err)
	}

	doc1 := struct {
		Text           string
		IgnoredText    string
		Numeric        float64
		IgnoredNumeric float64
		Date           time.Time
		IgnoredDate    time.Time
	}{
		Text:           "valid text",
		IgnoredText:    "ignored text",
		Numeric:        10,
		IgnoredNumeric: 20,
		Date:           time.Unix(1, 0),
		IgnoredDate:    time.Unix(2, 0),
	}

	err = index.Index("a", doc1)
	if err != nil {
		t.Fatal(err)
	}

	fields, err := index.Fields()
	if err != nil {
		t.Fatal(err)
	}
	sort.Strings(fields)
	expectedFields := []string{"Date", "Numeric", "Text", "_all"}
	if len(fields) != len(expectedFields) {
		t.Fatalf("invalid field count: %d", len(fields))
	}
	for i, expected := range expectedFields {
		if expected != fields[i] {
			t.Fatalf("unexpected field[%d]: %s", i, fields[i])
		}
	}

	err = index.Close()
	if err != nil {
		t.Fatal(err)
	}
}
示例#20
0
func (b *BPFSniffer) ReadPacketData() ([]byte, gopacket.CaptureInfo, error) {
	var err error
	if b.readBytesConsumed >= b.lastReadLen {
		b.readBytesConsumed = 0
		b.readBuffer = make([]byte, b.options.ReadBufLen)
		b.lastReadLen, err = syscall.Read(b.fd, b.readBuffer)
		if err != nil {
			b.lastReadLen = 0
			return nil, gopacket.CaptureInfo{}, err
		}
	}
	hdr := (*unix.BpfHdr)(unsafe.Pointer(&b.readBuffer[b.readBytesConsumed]))
	frameStart := b.readBytesConsumed + int(hdr.Hdrlen)
	b.readBytesConsumed += bpfWordAlign(int(hdr.Hdrlen) + int(hdr.Caplen))

	if frameStart+int(hdr.Caplen) > len(b.readBuffer) {
		captureInfo := gopacket.CaptureInfo{
			Timestamp:     time.Unix(int64(hdr.Tstamp.Sec), int64(hdr.Tstamp.Usec)*1000),
			CaptureLength: 0,
			Length:        0,
		}
		return nil, captureInfo, fmt.Errorf("BPF captured frame received with corrupted BpfHdr struct.")
	}

	rawFrame := b.readBuffer[frameStart : frameStart+int(hdr.Caplen)]
	captureInfo := gopacket.CaptureInfo{
		Timestamp:     time.Unix(int64(hdr.Tstamp.Sec), int64(hdr.Tstamp.Usec)*1000),
		CaptureLength: len(rawFrame),
		Length:        len(rawFrame),
	}
	return rawFrame, captureInfo, nil
}
示例#21
0
func SessionMiddleware(handler RequestHandler, context *RequestContext) {
	cookie, err := context.Request.Cookie("SID")
	if err == nil && len(cookie.Value) > 0 {
		session := GetSession(cookie.Value, context.sessionCache)
		if session == nil {
			cookie.Value = ""
			cookie.Expires = time.Unix(0, 0)
			http.SetCookie(context.Writer, cookie)
		} else if time.Now().After(session.expiration) {
			session.Expire()
			cookie.Value = ""
			cookie.Expires = time.Unix(0, 0)
			http.SetCookie(context.Writer, cookie)
		} else {
			context.Session = session
			if time.Now().After(session.expiration.Add(SessionUpdateWindow)) {
				session.expiration = time.Now().Add(SessionDuration)
				cookie.Expires = session.expiration
				session.Store()
				http.SetCookie(context.Writer, cookie)
			}
		}
	}
	handler(context)
}
示例#22
0
func lobbyInitializeEndPoin(c *gin.Context) {
	roomIDs, _ := getNewRoomIDs(0, 10)

	roomList := make([]interface{}, len(roomIDs))
	for i, roomID := range roomIDs {
		raw, _ := getRoomRaw(roomID)
		username, err := getUsername(raw.OwnerID)
		if err != nil {
			continue
		}
		roomList[i] = struct {
			ID             int
			Name           string
			Description    string
			CreationTime   string
			LastUpdateTime string
			IsPrivate      bool
			Members        int
			OwnerName      string
		}{
			ID:             raw.ID,
			Name:           raw.Name,
			Description:    raw.Description,
			CreationTime:   time.Unix(raw.CreationTime, 0).Format(TIME_LAYOUT),
			LastUpdateTime: time.Unix(raw.LastUpdateTime, 0).Format(TIME_LAYOUT),
			IsPrivate:      raw.IsPrivate,
			Members:        raw.Members,
			OwnerName:      username,
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"roomList": roomList,
	})
}
示例#23
0
func exportRange(start int64, end int64, filename string) (err error) {
	if !*force {
		if _, err := os.Stat(filename); err == nil {
			if *verbose {
				log.Printf("File %s already exists - skipping.", filename)
			}
			return err
		}
	}
	timeReadings, err := dbclient.GetFrequenciesBetween(*meterID,
		time.Unix(start, 0), time.Unix(end, 0))
	if err != nil {
		err = fmt.Errorf("Failed to query database: ", err.Error())
		return
	}
	sort.Sort(defluxio.ByTimestamp(timeReadings))

	log.Printf("Exporting %d readings [%d, %d] into file %s",
		len(timeReadings), start, end, filename)

	if tsve, err := defluxio.NewTsvExporter(filename); err != nil {
		return fmt.Errorf("Cannot create exporter for file %s ", filename)
	} else {
		if err = tsve.ExportDataset(timeReadings); err != nil {
			return fmt.Errorf("Failed to export dataset: %s ", err.Error())
		}
	}
	return
}
示例#24
0
func TestReleaseList(t *testing.T) {
	provider := StubAwsProvider(
		describeStacksCycle,

		releasesQueryCycle,
	)
	defer provider.Close()

	r, err := provider.ReleaseList("httpd", 20)

	assert.Nil(t, err)

	assert.EqualValues(t, structs.Releases{
		structs.Release{
			Id:       "RVFETUHHKKD",
			App:      "httpd",
			Build:    "BHINCLZYYVN",
			Env:      "foo=bar",
			Manifest: "web:\n  image: httpd\n  ports:\n  - 80:80\n",
			Created:  time.Unix(1459780542, 627770380).UTC(),
		},
		structs.Release{
			Id:       "RFVZFLKVTYO",
			App:      "httpd",
			Build:    "BNOARQMVHUO",
			Env:      "foo=bar",
			Manifest: "web:\n  image: httpd\n  ports:\n  - 80:80\n",
			Created:  time.Unix(1459709199, 166694813).UTC(),
		},
	}, r)
}
示例#25
0
func TestBulkSmallBatch(t *testing.T) {
	InitTests(true)
	c := NewTestConn()

	date := time.Unix(1257894000, 0)
	data := map[string]interface{}{"name": "smurfs", "age": 22, "date": time.Unix(1257894000, 0)}

	// Now tests small batches
	indexer := c.NewBulkIndexer(1)
	indexer.BufferDelayMax = 100 * time.Millisecond
	indexer.BulkMaxDocs = 2
	messageSets = 0
	indexer.Sender = func(buf *bytes.Buffer) error {
		messageSets += 1
		return indexer.Send(buf)
	}
	indexer.Start()
	<-time.After(time.Millisecond * 20)

	indexer.Index("users", "user", "2", "", &date, data, true)
	indexer.Index("users", "user", "3", "", &date, data, true)
	indexer.Index("users", "user", "4", "", &date, data, true)
	<-time.After(time.Millisecond * 200)
	//	indexer.Flush()
	indexer.Stop()
	assert.T(t, messageSets == 2, fmt.Sprintf("Should have sent 2 message sets %d", messageSets))

}
示例#26
0
func TestRemoveVehiclesBeforeTime(t *testing.T) {
	RunStorageTest(t, func(db *sqlx.DB, t *testing.T) {
		var recentDate int64 = 1460432740083 / 1000
		var oldDate int64 = 1420919252102 / 1000
		var newVehicle = muni.Vehicle{ID: "1234", TimeReceived: time.Unix(recentDate, 0)}
		var newVehicle2 = muni.Vehicle{ID: "1234", TimeReceived: time.Unix(recentDate, 0).Add(-time.Minute)}
		var oldVehicle = muni.Vehicle{ID: "1234", TimeReceived: time.Unix(oldDate, 0)}

		InsertVehicle(db, &newVehicle)
		InsertVehicle(db, &newVehicle2)
		InsertVehicle(db, &oldVehicle)

		RemoveVehiclesOlderThan(db, time.Unix(recentDate, 0).Add(-time.Second))

		v, err := GetVehiclesByID(db, "1234")

		if err != nil {
			t.Error(err)
		}

		if len(v) != 1 {
			t.Error("Wrong number of items returned")
		}
	})
}
示例#27
0
文件: api.go 项目: peekeri/influxdb
func (self *HttpServer) createShard(w libhttp.ResponseWriter, r *libhttp.Request) {
	self.tryAsClusterAdmin(w, r, func(u User) (int, interface{}) {
		newShards := &newShardInfo{}
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			return libhttp.StatusInternalServerError, err.Error()
		}
		err = json.Unmarshal(body, &newShards)
		if err != nil {
			return libhttp.StatusInternalServerError, err.Error()
		}
		shards := make([]*cluster.NewShardData, 0)

		shardType := cluster.SHORT_TERM
		if newShards.LongTerm {
			shardType = cluster.LONG_TERM
		}
		for _, s := range newShards.Shards {
			newShardData := &cluster.NewShardData{
				StartTime: time.Unix(newShards.StartTime, 0),
				EndTime:   time.Unix(newShards.EndTime, 0),
				ServerIds: s.ServerIds,
				Type:      shardType,
			}
			shards = append(shards, newShardData)
		}
		_, err = self.raftServer.CreateShards(shards)
		if err != nil {
			return libhttp.StatusInternalServerError, err.Error()
		}
		return libhttp.StatusAccepted, nil
	})
}
示例#28
0
文件: plugin.go 项目: yosisa/fluxion
func parseTime(v interface{}) (t time.Time, err error) {
	var n int64
	switch typed := v.(type) {
	case []byte:
		err = t.UnmarshalBinary(typed)
		return
	case string:
		err = t.UnmarshalBinary([]byte(typed))
		return
	case int64:
		n = typed
	case uint64:
		n = int64(typed)
	case float64:
		nsec := int64((typed - float64(int64(typed))) * 1e9)
		t = time.Unix(int64(typed), nsec)
		return
	default:
		if n, err = strconv.ParseInt(fmt.Sprintf("%v", typed), 10, 64); err != nil {
			return
		}
	}
	t = time.Unix(n, 0)
	return
}
示例#29
0
func TestVersion(t *testing.T) {
	v := new(Version)
	v.Version = uint16(1)
	v.Timestamp = time.Unix(0, 0)
	v.IpAddress = net.ParseIP("1.2.3.4")
	v.Port = uint16(4444)
	v.UserAgent = "Hello World!"

	verBytes := v.GetBytes()
	if len(verBytes) != verLen+12 {
		fmt.Println("Incorrect Byte Length: ", verBytes)
		t.Fail()
	}

	v2 := new(Version)
	err := v2.FromBytes(verBytes)
	if err != nil {
		fmt.Println("Error Decoding: ", err)
		t.FailNow()
	}

	if v2.Version != 1 || v2.Timestamp != time.Unix(0, 0) || v2.IpAddress.String() != "1.2.3.4" || v2.Port != 4444 || v2.UserAgent != "Hello World!" {
		fmt.Println("Incorrect decoded version: ", v2)
		t.Fail()
	}
}
示例#30
0
func TestFileStore_SeekToDesc_End(t *testing.T) {
	fs := tsm1.NewFileStore("")

	// Setup 3 files
	data := []keyValues{
		keyValues{"cpu", []tsm1.Value{tsm1.NewValue(time.Unix(0, 0), 1.0)}},
		keyValues{"cpu", []tsm1.Value{tsm1.NewValue(time.Unix(1, 0), 2.0)}},
		keyValues{"cpu", []tsm1.Value{tsm1.NewValue(time.Unix(2, 0), 3.0)}},
	}

	files, err := newFiles(data...)
	if err != nil {
		t.Fatalf("unexpected error creating files: %v", err)
	}

	fs.Add(files...)

	c := fs.KeyCursor("cpu")
	values, err := c.SeekTo(time.Unix(2, 0), false)
	if err != nil {
		t.Fatalf("unexpected error reading values: %v", err)
	}

	exp := data[2]
	if got, exp := len(values), len(exp.values); got != exp {
		t.Fatalf("value length mismatch: got %v, exp %v", got, exp)
	}

	for i, v := range exp.values {
		if got, exp := values[i].Value(), v.Value(); got != exp {
			t.Fatalf("read value mismatch(%d): got %v, exp %d", i, got, exp)
		}
	}
}