Esempio n. 1
0
func TestUTPPingPong(t *testing.T) {
	defer goroutineLeakCheck(t)()
	s, err := NewSocket("udp", "localhost:0")
	require.NoError(t, err)
	defer s.Close()
	pingerClosed := make(chan struct{})
	go func() {
		defer close(pingerClosed)
		b, err := Dial(s.Addr().String())
		require.NoError(t, err)
		defer b.Close()
		n, err := b.Write([]byte("ping"))
		require.NoError(t, err)
		require.EqualValues(t, 4, n)
		buf := make([]byte, 4)
		b.Read(buf)
		require.EqualValues(t, "pong", buf)
		log.Printf("got pong")
	}()
	a, err := s.Accept()
	require.NoError(t, err)
	defer a.Close()
	log.Printf("accepted %s", a)
	buf := make([]byte, 42)
	n, err := a.Read(buf)
	require.NoError(t, err)
	require.EqualValues(t, "ping", buf[:n])
	log.Print("got ping")
	n, err = a.Write([]byte("pong"))
	require.NoError(t, err)
	require.Equal(t, 4, n)
	log.Print("waiting for pinger to close")
	<-pingerClosed
}
Esempio n. 2
0
func (s *watcherTestSuite) Test_DynamicUpdateRestoresGoodState() {
	someInt := flagz.DynInt64(s.flagSet, "someint", 1337, "some int usage")
	someFloat := flagz.DynFloat64(s.flagSet, "somefloat", 1.337, "some int usage")
	s.setFlagzValue("someint", "2015")
	require.NoError(s.T(), s.watcher.Initialize())
	require.NoError(s.T(), s.watcher.Start())
	require.EqualValues(s.T(), 2015, someInt.Get(), "int flag should change value")
	require.EqualValues(s.T(), 1.337, someFloat.Get(), "float flag should not change value")

	// Bad update causing a rollback.
	s.setFlagzValue("someint", "randombleh")
	eventually(s.T(), 1*time.Second,
		assert.ObjectsAreEqualValues,
		"2015",
		func() interface{} {
			return s.getFlagzValue("someint")
		},
		"someint failure should revert etcd value to 2015")

	// Make sure we can continue updating.
	s.setFlagzValue("someint", "2016")
	s.setFlagzValue("somefloat", "3.14")
	eventually(s.T(), 1*time.Second,
		assert.ObjectsAreEqualValues, int64(2016),
		func() interface{} { return someInt.Get() },
		"someint value should change, after rolled back")
	eventually(s.T(), 1*time.Second,
		assert.ObjectsAreEqualValues, float64(3.14),
		func() interface{} { return someFloat.Get() },
		"somefloat value should change")

}
Esempio n. 3
0
func TestTransactionSingleConnection(t *testing.T) {
	db, _ := sql.Open("sqlrpc", serverAddr)
	defer db.Close()
	db.Exec("drop table if exists a")
	tx, _ := db.Begin()
	tx.Exec("create table a(b)")
	tx.Exec("insert into a values(?)", 1)
	t.Log(time.Now())
	row := tx.QueryRow("select * from a where b < ?", 2)
	var i int
	err := row.Scan(&i)
	t.Log(time.Now())
	require.NoError(t, err)
	require.EqualValues(t, 1, i)
	tx.Exec("insert into a values(?)", 2)
	rows, err := tx.Query("select b from a where b > ?", 0)
	require.NoError(t, err)
	cols, _ := rows.Columns()
	require.EqualValues(t, []string{"b"}, cols)
	require.True(t, rows.Next())
	rows.Scan(&i)
	require.EqualValues(t, 1, i)
	require.True(t, rows.Next())
	rows.Scan(&i)
	require.EqualValues(t, 2, i)
	require.False(t, rows.Next())
	tx.Rollback()
}
Esempio n. 4
0
func TestQuery(t *testing.T) {
	dir1, dir2, _, err := prepare()
	require.NoError(t, err)
	defer closeAll(dir1, dir2)

	// Parse GQL into internal query representation.
	gq, _, err := gql.Parse(q0)
	require.NoError(t, err)

	ctx := context.Background()
	g, err := query.ToSubGraph(ctx, gq)
	require.NoError(t, err)

	// Test internal query representation.
	require.EqualValues(t, childAttrs(g), []string{"follows", "_xid_", "status"})
	require.EqualValues(t, childAttrs(g.Children[0]), []string{"_xid_", "status"})

	ch := make(chan error)
	go query.ProcessGraph(ctx, g, nil, ch)
	err = <-ch
	require.NoError(t, err)

	var l query.Latency
	js, err := g.ToJSON(&l)
	require.NoError(t, err)
	fmt.Println(string(js))
}
Esempio n. 5
0
// Ensure that no race exists between sending a bitfield, and a subsequent
// Have that would potentially alter it.
func TestSendBitfieldThenHave(t *testing.T) {
	r, w := io.Pipe()
	c := &connection{
		t: &Torrent{
			cl: &Client{},
		},
		rw: struct {
			io.Reader
			io.Writer
		}{r, w},
		outgoingUnbufferedMessages: list.New(),
	}
	go c.writer(time.Minute)
	c.mu().Lock()
	c.Bitfield([]bool{false, true, false})
	c.mu().Unlock()
	c.mu().Lock()
	c.Have(2)
	c.mu().Unlock()
	b := make([]byte, 15)
	n, err := io.ReadFull(r, b)
	c.mu().Lock()
	// This will cause connection.writer to terminate.
	c.closed.Set()
	c.mu().Unlock()
	require.NoError(t, err)
	require.EqualValues(t, 15, n)
	// Here we see that the bitfield doesn't have piece 2 set, as that should
	// arrive in the following Have message.
	require.EqualValues(t, "\x00\x00\x00\x02\x05@\x00\x00\x00\x05\x04\x00\x00\x00\x02", string(b))
}
Esempio n. 6
0
func TestSnapshot(t *testing.T) {
	path, err := ioutil.TempDir("", "storetest_")
	require.NoError(t, err)
	defer os.RemoveAll(path)

	s, err := NewStore(path)
	require.NoError(t, err)

	k := []byte("mykey")
	require.NoError(t, s.SetOne(k, []byte("neo")))

	snapshot := s.NewSnapshot() // Snapshot will contain neo, not trinity.
	require.NoError(t, s.SetOne(k, []byte("trinity")))

	// Before setting snapshot, do a get. Expect to get trinity.
	val, err := s.Get(k)
	require.NoError(t, err)
	require.EqualValues(t, val.Data(), "trinity")

	s.SetSnapshot(snapshot)
	// After setting snapshot, we expect to get neo.
	val, err = s.Get(k)
	require.NoError(t, err)
	require.EqualValues(t, val.Data(), "neo")

	s.SetSnapshot(nil)
	// After clearing snapshot, we expect to get trinity again.
	val, err = s.Get(k)
	require.NoError(t, err)
	require.EqualValues(t, val.Data(), "trinity")
}
Esempio n. 7
0
func TestSortInts(t *testing.T) {
	list := getInput(Int32ID, []string{"22", "111", "11", "212"})
	ul := getUIDList(4)
	require.NoError(t, int32Type.Sort(list, ul, false))
	require.EqualValues(t, []uint64{300, 100, 200, 400}, ul.Uids)
	require.EqualValues(t, []string{"11", "22", "111", "212"},
		toString(t, list))
}
Esempio n. 8
0
func TestSortByteArrays(t *testing.T) {
	list := getInput(BytesID, []string{"bb", "aaa", "aa", "bab"})
	ul := getUIDList(4)
	require.NoError(t, byteArrayType.Sort(list, ul, false))
	require.EqualValues(t, []uint64{300, 200, 400, 100}, ul.Uids)
	require.EqualValues(t, []string{"aa", "aaa", "bab", "bb"},
		toString(t, list))
}
Esempio n. 9
0
func TestUnmarshalPex(t *testing.T) {
	var pem peerExchangeMessage
	err := bencode.Unmarshal([]byte("d5:added12:\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0ce"), &pem)
	require.NoError(t, err)
	require.EqualValues(t, 2, len(pem.Added))
	require.EqualValues(t, 1286, pem.Added[0].Port)
	require.EqualValues(t, 0x100*0xb+0xc, pem.Added[1].Port)
}
Esempio n. 10
0
func TestAddMutation_jchiu3(t *testing.T) {
	key := x.DataKey("value", 10)
	dir, err := ioutil.TempDir("", "storetest_")
	require.NoError(t, err)
	defer os.RemoveAll(dir)

	ps, err := store.NewStore(dir)
	require.NoError(t, err)
	Init(ps)
	ol := getNew(key, ps)

	// Set value to cars and merge to RocksDB.
	edge := &task.DirectedEdge{
		Value: []byte("cars"),
		Label: "jchiu",
	}
	addMutation(t, ol, edge, Set)
	require.Equal(t, 1, ol.Length(0))
	merged, err := ol.CommitIfDirty(context.Background())
	require.NoError(t, err)
	require.True(t, merged)
	require.EqualValues(t, 1, ol.Length(0))
	checkValue(t, ol, "cars")

	// Del a value cars and but don't merge.
	edge = &task.DirectedEdge{
		Value: []byte("cars"),
		Label: "jchiu",
	}
	addMutation(t, ol, edge, Del)
	require.Equal(t, 0, ol.Length(0))

	// Set value to newcars, but don't merge yet.
	edge = &task.DirectedEdge{
		Value: []byte("newcars"),
		Label: "jchiu",
	}
	addMutation(t, ol, edge, Set)
	require.EqualValues(t, 1, ol.Length(0))
	checkValue(t, ol, "newcars")

	// Del a value othercars and but don't merge.
	edge = &task.DirectedEdge{
		Value: []byte("othercars"),
		Label: "jchiu",
	}
	addMutation(t, ol, edge, Del)
	require.NotEqual(t, 0, ol.Length(0))
	checkValue(t, ol, "newcars")

	// Del a value newcars and but don't merge.
	edge = &task.DirectedEdge{
		Value: []byte("newcars"),
		Label: "jchiu",
	}
	addMutation(t, ol, edge, Del)
	require.Equal(t, 0, ol.Length(0))
}
Esempio n. 11
0
func TestSortFloatsDesc(t *testing.T) {
	list := getInput(FloatID, []string{"22.2", "11.2", "11.5", "2.12"})
	ul := getUIDList(4)
	require.NoError(t, floatType.Sort(list, ul, true))
	require.EqualValues(t, []uint64{100, 300, 200, 400}, ul.Uids)
	require.EqualValues(t,
		[]string{"2.22E+01", "1.15E+01", "1.12E+01", "2.12E+00"},
		toString(t, list))
}
Esempio n. 12
0
func TestSortDates(t *testing.T) {
	in := []string{"2022-01-01", "2022-02-03", "2021-01-05", "2021-01-07"}
	list := getInput(DateID, in)
	ul := getUIDList(4)
	require.NoError(t, dateType.Sort(list, ul, false))
	require.EqualValues(t, []uint64{300, 400, 100, 200}, ul.Uids)
	require.EqualValues(t,
		[]string{"2021-01-05", "2021-01-07", "2022-01-01", "2022-02-03"},
		toString(t, list))
}
Esempio n. 13
0
func TestMarshalAnnounceResponse(t *testing.T) {
	peers := util.CompactIPv4Peers{
		{[]byte{127, 0, 0, 1}, 2},
		{[]byte{255, 0, 0, 3}, 4},
	}
	b, err := peers.MarshalBinary()
	require.NoError(t, err)
	require.EqualValues(t,
		"\x7f\x00\x00\x01\x00\x02\xff\x00\x00\x03\x00\x04",
		b)
	require.EqualValues(t, 12, binary.Size(AnnounceResponseHeader{}))
}
Esempio n. 14
0
func TestDecoderConsecutive(t *testing.T) {
	d := NewDecoder(bytes.NewReader([]byte("i1ei2e")))
	var i int
	err := d.Decode(&i)
	require.NoError(t, err)
	require.EqualValues(t, 1, i)
	err = d.Decode(&i)
	require.NoError(t, err)
	require.EqualValues(t, 2, i)
	err = d.Decode(&i)
	require.Equal(t, io.EOF, err)
}
Esempio n. 15
0
func TestKeys(t *testing.T) {
	k, ok := Keys(map[string]string{"hi": "", "ho": ""})
	require.True(t, ok)
	require.EqualValues(t, []string{"hi", "ho"}, k)
	k, ok = Keys(map[int]string{2: "", 3: ""})
	require.False(t, ok)
	k, ok = Keys(TestStruct{})
	require.True(t, ok)
	require.EqualValues(t, []string{"A1", "A2"}, k)
	k, ok = Keys(TestStruct2{})
	require.True(t, ok)
	require.EqualValues(t, []string{"A2", "lol"}, k)
}
Esempio n. 16
0
func TestSortDateTimes(t *testing.T) {
	in := []string{
		"2016-01-02T15:04:05",
		"2006-01-02T15:04:05",
		"2006-01-02T15:04:06",
		"2006-01-02T15:04:01",
	}
	list := getInput(DateTimeID, in)
	ul := getUIDList(4)
	require.NoError(t, dateTimeType.Sort(list, ul, false))
	require.EqualValues(t, []uint64{400, 200, 300, 100}, ul.Uids)
	require.EqualValues(t,
		[]string{"2006-01-02T15:04:01Z", "2006-01-02T15:04:05Z",
			"2006-01-02T15:04:06Z", "2016-01-02T15:04:05Z"},
		toString(t, list))
}
Esempio n. 17
0
func TestDescriptorTransform(t *testing.T) {

	hSink := dummySink()

	ld := core.LabelDescriptor{
		Key:         "k1",
		Description: "d1",
	}
	smd := core.MetricDescriptor{
		Name:      "test/metric/1",
		Units:     core.UnitsBytes,
		ValueType: core.ValueInt64,
		Type:      core.MetricGauge,
		Labels:    []core.LabelDescriptor{ld},
	}

	md := hSink.descriptorToDefinition(&smd)

	assert.Equal(t, smd.Name, md.Id)
	assert.Equal(t, 3, len(md.Tags)) // descriptorTag, unitsTag, typesTag, k1

	assert.Equal(t, smd.Units.String(), md.Tags[unitsTag])
	assert.Equal(t, "d1", md.Tags["k1_description"])

	smd.Type = core.MetricCumulative

	md = hSink.descriptorToDefinition(&smd)
	assert.EqualValues(t, md.Type, metrics.Counter)
}
Esempio n. 18
0
func testCycle(t *testing.T, base interface{}, ff interface{}) {
	setXValue(t, base)

	buf, err := json.MarshalIndent(base, " ", "  ")
	require.NoError(t, err, "base[%T] failed to Marshal", base)

	ffDst := emptyInterface(ff)
	baseDst := emptyInterface(base)

	err = json.Unmarshal(buf, ffDst)
	errGo := json.Unmarshal(buf, baseDst)
	if outputFileOnError && err != nil {
		typeName := reflect.Indirect(reflect.ValueOf(base)).Type().String()
		file, err := os.Create(fmt.Sprintf("fail-%s-unmarshal-decoder-input.json", typeName))
		if err == nil {
			file.Write(buf)
			file.Close()
		}
		if errGo == nil {
			file, err := os.Create(fmt.Sprintf("fail-%s-unmarshal-decoder-output-base.txt", typeName))
			if err == nil {
				fmt.Fprintf(file, "%#v", baseDst)
				file.Close()
			}
		}
	}
	require.Nil(t, err, "json.Unmarshal of encoded ff[%T],\nErrors golang:%v,\nffjson:%v", ff, errGo, err)
	require.Nil(t, errGo, "json.Unmarshal of encoded ff[%T],\nerrors golang:%v,\nffjson:%v", base, errGo, err)

	require.EqualValues(t, baseDst, ffDst, "json.Unmarshal of base[%T] into ff[%T]", base, ff)
}
Esempio n. 19
0
func TestDebug1(t *testing.T) {
	dir, dir2, _ := populateGraph(t)
	defer os.RemoveAll(dir)
	defer os.RemoveAll(dir2)

	// Alright. Now we have everything set up. Let's create the query.
	query := `
		{
			debug(_uid_:0x01) {
				name
				gender
				alive
				friend {
					_count_
				}
			}
		}
	`

	js := processToJSON(t, query)
	var mp map[string]interface{}
	require.NoError(t, json.Unmarshal([]byte(js), &mp))

	resp := mp["debug"]
	uid := resp.([]interface{})[0].(map[string]interface{})["_uid_"].(string)
	require.EqualValues(t, "0x1", uid)

	latency := mp["server_latency"]
	require.NotNil(t, latency)
	_, ok := latency.(map[string]interface{})
	require.True(t, ok)
}
Esempio n. 20
0
// writes 25,000 metrics to the listener with 10 different writers
func TestWriteHTTPHighTraffic(t *testing.T) {
	listener := &HttpListener{ServiceAddress: ":8286"}
	parser, _ := parsers.NewInfluxParser()
	listener.SetParser(parser)

	acc := &testutil.Accumulator{}
	require.NoError(t, listener.Start(acc))
	defer listener.Stop()

	time.Sleep(time.Millisecond * 25)

	// post many messages to listener
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			for i := 0; i < 500; i++ {
				resp, err := http.Post("http://localhost:8286/write?db=mydb", "", bytes.NewBuffer([]byte(testMsgs)))
				require.NoError(t, err)
				require.EqualValues(t, 204, resp.StatusCode)
			}
			wg.Done()
		}()
	}

	wg.Wait()
	time.Sleep(time.Millisecond * 50)
	listener.Gather(acc)

	require.Equal(t, int64(25000), int64(acc.NMetrics()))
}
Esempio n. 21
0
func TestToProtoMultiRoot(t *testing.T) {
	dir, dir2, _ := populateGraph(t)
	defer os.RemoveAll(dir)
	defer os.RemoveAll(dir2)

	query := `
    {
      me(anyof("name", "Michonne Rick Glenn")) {
        name
      }
    }
  `

	gq, _, err := gql.Parse(query)
	require.NoError(t, err)

	ctx := context.Background()
	sg, err := ToSubGraph(ctx, gq)
	require.NoError(t, err)

	ch := make(chan error)
	go ProcessGraph(ctx, sg, nil, ch)
	err = <-ch
	require.NoError(t, err)

	var l Latency
	pb, err := sg.ToProtocolBuffer(&l)
	require.NoError(t, err)

	expectedPb := `attribute: "_root_"
children: <
  attribute: "me"
  properties: <
    prop: "name"
    value: <
      str_val: "Michonne"
    >
  >
>
children: <
  attribute: "me"
  properties: <
    prop: "name"
    value: <
      str_val: "Rick Grimes"
    >
  >
>
children: <
  attribute: "me"
  properties: <
    prop: "name"
    value: <
      str_val: "Glenn Rhee"
    >
  >
>
`
	require.EqualValues(t, expectedPb, proto.MarshalTextString(pb))
}
Esempio n. 22
0
func assertFailedEntry(t *testing.T, expected string, entries []crossdock.Entry) {
	require.True(t, len(entries) > 0, "Must have some entries %+v", entries)
	entry := entries[len(entries)-1]
	require.EqualValues(t, "failed", entry["status"], "Entries: %v", entries)
	require.NotEmpty(t, entry["output"], "Entries: %v", entries)
	output := entry["output"].(string)
	assert.True(t, strings.Contains(output, expected), "Output must contain %s: %s", expected, output)
}
Esempio n. 23
0
func (s *endpointTestSuite) assertListContainsOnly(flagList []string, list *flagSetJSON) {
	existing := []string{}
	for _, f := range list.Flags {
		existing = append(existing, f.Name)
	}
	sort.Strings(flagList)
	require.EqualValues(s.T(), flagList, existing, "expected set of listed flags must match")
}
Esempio n. 24
0
func TestParseArgs(t *testing.T) {
	t.Log("simple plugin command")
	{
		args := []string{"bitrise", ":example"}
		pluginName, pluginArgs, isPlugin := ParseArgs(args)
		require.Equal(t, true, isPlugin)
		require.Equal(t, "example", pluginName)
		require.Equal(t, 0, len(pluginArgs))
	}

	t.Log("simple plugin command - with bitrise flags")
	{
		args := []string{"bitrise", "-l", "debug", ":example"}
		pluginName, pluginArgs, isPlugin := ParseArgs(args)
		require.Equal(t, true, isPlugin)
		require.Equal(t, "example", pluginName)
		require.Equal(t, 0, len(pluginArgs))
	}

	t.Log("plugin command - with args")
	{
		args := []string{"bitrise", ":example", "hello", "bitrise"}
		pluginName, pluginArgs, isPlugin := ParseArgs(args)
		require.Equal(t, true, isPlugin)
		require.Equal(t, "example", pluginName)
		require.EqualValues(t, []string{"hello", "bitrise"}, pluginArgs)
	}

	t.Log("plugin command - with falg")
	{
		args := []string{"bitrise", ":example", "hello", "--name", "bitrise"}
		pluginName, pluginArgs, isPlugin := ParseArgs(args)
		require.Equal(t, true, isPlugin)
		require.Equal(t, "example", pluginName)
		require.EqualValues(t, []string{"hello", "--name", "bitrise"}, pluginArgs)
	}

	t.Log("not plugin command")
	{
		args := []string{"bitrise", "hello", "bitrise"}
		pluginName, pluginArgs, isPlugin := ParseArgs(args)
		require.Equal(t, false, isPlugin)
		require.Equal(t, "", pluginName)
		require.Equal(t, 0, len(pluginArgs))
	}
}
Esempio n. 25
0
func TestCancelRequestOptimized(t *testing.T) {
	r, w := io.Pipe()
	c := &connection{
		PeerMaxRequests: 1,
		peerPieces: func() bitmap.Bitmap {
			var bm bitmap.Bitmap
			bm.Set(1, true)
			return bm
		}(),
		rw: struct {
			io.Reader
			io.Writer
		}{
			Writer: w,
		},
		conn: new(net.TCPConn),
		// For the locks
		t: &Torrent{cl: &Client{}},
	}
	assert.Len(t, c.Requests, 0)
	c.Request(newRequest(1, 2, 3))
	require.Len(t, c.Requests, 1)
	// Posting this message should removing the pending Request.
	require.True(t, c.Cancel(newRequest(1, 2, 3)))
	assert.Len(t, c.Requests, 0)
	// Check that write optimization filters out the Request, due to the
	// Cancel. We should have received an Interested, due to the initial
	// request, and then keep-alives until we close the connection.
	go c.writer(0)
	b := make([]byte, 9)
	n, err := io.ReadFull(r, b)
	require.NoError(t, err)
	require.EqualValues(t, len(b), n)
	require.EqualValues(t, "\x00\x00\x00\x01\x02"+"\x00\x00\x00\x00", string(b))
	time.Sleep(time.Millisecond)
	c.mu().Lock()
	c.Close()
	c.mu().Unlock()
	w.Close()
	b, err = ioutil.ReadAll(r)
	require.NoError(t, err)
	// A single keep-alive will have gone through, as writer would be stuck
	// trying to flush it, and then promptly close.
	require.EqualValues(t, "\x00\x00\x00\x00", string(b))
}
Esempio n. 26
0
func TestGroupByKey(t *testing.T) {
	var ks []byte
	gb := GroupBy(StringIterator("AAAABBBCCDAABBB"), nil)
	for gb.Next() {
		ks = append(ks, gb.Value().(Group).Key().(byte))
	}
	t.Log(ks)
	require.EqualValues(t, "ABCDAB", ks)
}
Esempio n. 27
0
func TestDBGetChecksum(t *testing.T) {
	tempBaseDir, err := ioutil.TempDir("", "notary-test-")
	_, store := SetUpSQLite(t, tempBaseDir)
	defer os.RemoveAll(tempBaseDir)

	ts := data.SignedTimestamp{
		Signatures: make([]data.Signature, 0),
		Signed: data.Timestamp{
			SignedCommon: data.SignedCommon{
				Type:    data.TUFTypes[data.CanonicalTimestampRole],
				Version: 1,
				Expires: data.DefaultExpires(data.CanonicalTimestampRole),
			},
		},
	}
	j, err := json.Marshal(&ts)
	require.NoError(t, err)
	update := MetaUpdate{
		Role:    data.CanonicalTimestampRole,
		Version: 1,
		Data:    j,
	}
	checksumBytes := sha256.Sum256(j)
	checksum := hex.EncodeToString(checksumBytes[:])

	store.UpdateCurrent("gun", update)

	// create and add a newer timestamp. We're going to try and get the one
	// created above by checksum
	ts = data.SignedTimestamp{
		Signatures: make([]data.Signature, 0),
		Signed: data.Timestamp{
			SignedCommon: data.SignedCommon{
				Type:    data.TUFTypes[data.CanonicalTimestampRole],
				Version: 2,
				Expires: data.DefaultExpires(data.CanonicalTimestampRole),
			},
		},
	}
	newJ, err := json.Marshal(&ts)
	require.NoError(t, err)
	update = MetaUpdate{
		Role:    data.CanonicalTimestampRole,
		Version: 2,
		Data:    newJ,
	}

	store.UpdateCurrent("gun", update)

	cDate, data, err := store.GetChecksum("gun", data.CanonicalTimestampRole, checksum)
	require.NoError(t, err)
	require.EqualValues(t, j, data)
	// the creation 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)))
}
Esempio n. 28
0
func TestConvertToEdges(t *testing.T) {
	q1 := `_uid_:0x01 <type> _uid_:0x02 .
	       _uid_:0x01 <character> _uid_:0x03 .`
	nquads, err := convertToNQuad(context.Background(), q1)
	require.NoError(t, err)

	mr, err := convertToEdges(context.Background(), nquads)
	require.NoError(t, err)

	require.EqualValues(t, len(mr.edges), 2)
}
Esempio n. 29
0
func TestGet(t *testing.T) {
	path, err := ioutil.TempDir("", "storetest_")
	require.NoError(t, err)
	defer os.RemoveAll(path)

	s, err := NewStore(path)
	require.NoError(t, err)

	k := []byte("mykey")
	require.NoError(t, s.SetOne(k, []byte("neo")))

	val, err := s.Get(k)
	require.NoError(t, err)
	require.EqualValues(t, val.Data(), "neo")

	require.NoError(t, s.SetOne(k, []byte("the one")))
	val, err = s.Get(k)
	require.NoError(t, err)
	require.EqualValues(t, val.Data(), "the one")
}
Esempio n. 30
0
func TestToProtoFilterAnd(t *testing.T) {
	dir, dir2, _ := populateGraph(t)
	defer os.RemoveAll(dir)
	defer os.RemoveAll(dir2)

	// Alright. Now we have everything set up. Let's create the query.
	query := `
		{
			me(_uid_:0x01) {
				name
				gender
				friend @filter(anyof("name", "Andrea") && anyof("name", "Glenn Rhee")) {
					name
				}
			}
		}
	`

	gq, _, err := gql.Parse(query)
	require.NoError(t, err)

	ctx := context.Background()
	sg, err := ToSubGraph(ctx, gq)
	require.NoError(t, err)

	ch := make(chan error)
	go ProcessGraph(ctx, sg, nil, ch)
	err = <-ch
	require.NoError(t, err)

	var l Latency
	pb, err := sg.ToProtocolBuffer(&l)
	require.NoError(t, err)

	expectedPb := `attribute: "_root_"
children: <
  attribute: "me"
  properties: <
    prop: "name"
    value: <
      str_val: "Michonne"
    >
  >
  properties: <
    prop: "gender"
    value: <
      bytes_val: "female"
    >
  >
>
`
	require.EqualValues(t, expectedPb, proto.MarshalTextString(pb))
}