func TestDispose(t *testing.T) {
	assert := assert.New(t)
	b, err := New(0, 2, 100000, 10, func(str interface{}) uint {
		return uint(len(str.(string)))
	})
	assert.Nil(err)
	b.Put("a")
	b.Put("b")
	b.Put("c")
	wait := make(chan bool)
	go func() {
		batch1, err := b.Get()
		assert.Equal([]interface{}{"a", "b"}, batch1)
		assert.Nil(err)
		batch2, err := b.Get()
		assert.Equal([]interface{}{"c"}, batch2)
		assert.Nil(err)
		_, err = b.Get()
		assert.Equal(ErrDisposed, err)
		wait <- true
	}()

	b.Dispose()

	assert.Equal(ErrDisposed, b.Put("d"))
	assert.Equal(ErrDisposed, b.Flush())

	<-wait
}
Example #2
0
func TestMarkReset(t *testing.T) {
	runes := []rune("a;188.54.10.56;12.333")
	br := NewBufferedReader(runes)
	assert.NotNil(t, br)

	AssertNextRunes(t, br, 'a', ';')

	err := br.Mark()
	assert.Nil(t, err)
	AssertNextRunes(t, br, '1', '8', '8', '.', '5', '4', '.')
	br.Reset()

	err = br.Mark()
	assert.Nil(t, err)
	AssertNextRunes(t, br, '1', '8', '8', '.', '5', '4', '.', '1', '0', '.', '5', '6', ';')

	err = br.Mark()
	assert.Nil(t, err)
	AssertNextRunes(t, br, '1', '2', '.')
	br.Reset()

	err = br.Mark()
	assert.Nil(t, err)
	AssertNextRunes(t, br, '1', '2', '.', '3', '3', '3', EOF)
	br.Reset()
}
Example #3
0
func (suite *IntegrationMigrateSuite) TestMigrationStateStorageAndRetrieval() {
	transform, err := NewConvert(testdata.ConvertDestination1, false, false, NewNullLogger())
	assert.Nil(suite.T(), err)

	err = transform.ConvertDirectory(testdata.ConvertSource1)
	assert.Nil(suite.T(), err)

	up := NewUp(testdata.ConvertDestination1, suite.Target)
	err = up.Migrate()
	assert.Nil(suite.T(), err)

	state, err := suite.Target.GetStatus()
	assert.Nil(suite.T(), err)
	assert.NotNil(suite.T(), state.Migrations)
	assert.Equal(suite.T(), up.Migrations.Len(), state.Migrations.Len())

	first, err := state.Migrations.First()
	assert.Nil(suite.T(), err)
	var leaf ConfigLeaf
	for _, entry := range first.Content.Entries {
		if entry.Path == "/default/alice" {
			leaf = entry
		}
	}
	assert.NotNil(suite.T(), leaf)
}
func TestGet(t *testing.T) {
	q := New(10)

	q.Put(`test`)
	result, err := q.Get(2)
	if !assert.Nil(t, err) {
		return
	}

	assert.Len(t, result, 1)
	assert.Equal(t, `test`, result[0])
	assert.Equal(t, int64(0), q.Len())

	q.Put(`1`)
	q.Put(`2`)

	result, err = q.Get(1)
	if !assert.Nil(t, err) {
		return
	}

	assert.Len(t, result, 1)
	assert.Equal(t, `1`, result[0])
	assert.Equal(t, int64(1), q.Len())

	result, err = q.Get(2)
	if !assert.Nil(t, err) {
		return
	}

	assert.Equal(t, `2`, result[0])
}
Example #5
0
func TestCreateSpendsWithBurn(t *testing.T) {
	now := tNow()
	amt := wallet.Balance{10e6, 100}
	uxs := makeUxBalances([]wallet.Balance{
		wallet.Balance{1e6, 50},
		wallet.Balance{8e6, 40},
		wallet.Balance{2e6, 60},
	}, now)
	// Force them to get sorted
	uxs[2].Head.BkSeq = uint64(0)
	uxs[1].Head.BkSeq = uint64(1)
	uxs[0].Head.BkSeq = uint64(2)
	cuxs := append(coin.UxArray{}, uxs...)
	// Should spend 8e6,2e6 for the exact amount, but have to add 1e6 to
	// obtain +50 for a 50% fee
	spends, err := createSpends(now, uxs, amt, 0, 2)
	assert.Nil(t, err)
	assert.Equal(t, len(spends), 3)
	assert.Equal(t, spends, coin.UxArray{cuxs[2], cuxs[1], cuxs[0]})

	have := wallet.Balance{0, 0}
	for _, ux := range spends {
		have = have.Add(wallet.NewBalanceFromUxOut(now, &ux))
	}
	burn, change, err := calculateBurnAndChange(have.Hours, amt.Hours, 0, 2)
	assert.Equal(t, burn, uint64(50))
	assert.Equal(t, change, uint64(0))
	assert.Nil(t, err)
}
Example #6
0
func TestMetadataCreateAllDropAllError(t *testing.T) {
	accounts := Table(
		"account",
		Column("id", Type("UUID")),
		PrimaryKey("id"),
	)
	engine, err := New("postgres", postgresDsn)
	metadata := MetaData()

	engine.Dialect().SetEscaping(true)
	assert.Nil(t, err)
	metadata.AddTable(accounts)
	err = metadata.CreateAll(engine)
	assert.Nil(t, err)

	engineNew, err := New("postgres", postgresDsn)
	engineNew.Dialect().SetEscaping(true)
	metadataNew := MetaData()
	assert.Nil(t, err)
	metadataNew.AddTable(accounts)
	err = metadataNew.CreateAll(engineNew)
	assert.NotNil(t, err)

	err = metadataNew.DropAll(engine)
	assert.Nil(t, err)

	err = metadataNew.DropAll(engineNew)
	assert.NotNil(t, err)
}
Example #7
0
func TestIsSameFile(t *testing.T) {
	absPath, err := filepath.Abs("../tests/files/")

	assert.NotNil(t, absPath)
	assert.Nil(t, err)

	fileInfo1, err := os.Stat(absPath + "/logs/test.log")
	fileInfo2, err := os.Stat(absPath + "/logs/system.log")

	assert.Nil(t, err)
	assert.NotNil(t, fileInfo1)
	assert.NotNil(t, fileInfo2)

	file1 := &File{
		FileInfo: fileInfo1,
	}

	file2 := &File{
		FileInfo: fileInfo2,
	}

	file3 := &File{
		FileInfo: fileInfo2,
	}

	assert.False(t, file1.IsSameFile(file2))
	assert.False(t, file2.IsSameFile(file1))

	assert.True(t, file1.IsSameFile(file1))
	assert.True(t, file2.IsSameFile(file2))

	assert.True(t, file3.IsSameFile(file2))
	assert.True(t, file2.IsSameFile(file3))
}
Example #8
0
// Checks that PrepareNewMessage and Parse can manage two messages sharing one packet on the same stream
// It typically happens when a SOA is followed by AXFR
func TestParseTcp_errorDuplicateRequestsOnePacket(t *testing.T) {
	var private protos.ProtocolData
	dns := newDns(testing.Verbose())
	q := elasticATcp
	offset := 4

	concatRequest := append(q.request, q.request[:offset]...)
	packet := newPacket(forward, concatRequest)
	tcptuple := testTcpTuple()

	private = dns.Parse(packet, tcptuple, tcp.TcpDirectionOriginal, private)
	assert.Equal(t, 1, dns.transactions.Size(), "There should be one transaction.")

	packet = newPacket(forward, q.request[offset:])
	private = dns.Parse(packet, tcptuple, tcp.TcpDirectionOriginal, private)
	assert.Equal(t, 1, dns.transactions.Size(), "There should be one transaction.")

	m := expectResult(t, dns)
	assertRequest(t, m, q)
	assert.Equal(t, "tcp", mapValue(t, m, "transport"))
	assert.Equal(t, len(q.request), mapValue(t, m, "bytes_in"))
	assert.Nil(t, mapValue(t, m, "bytes_out"))
	assert.Nil(t, mapValue(t, m, "responsetime"))
	assert.Equal(t, common.ERROR_STATUS, mapValue(t, m, "status"))
	assert.Equal(t, DuplicateQueryMsg.Error(), mapValue(t, m, "notes"))
}
func (suite *OauthTestSuite) TestFindClientByClientID() {
	var (
		client *Client
		err    error
	)

	// When we try to find a client with a bogus client ID
	client, err = suite.service.FindClientByClientID("bogus")

	// Client object should be nil
	assert.Nil(suite.T(), client)

	// Correct error should be returned
	if assert.NotNil(suite.T(), err) {
		assert.Equal(suite.T(), ErrClientNotFound, err)
	}

	// When we try to find a client with a valid cliend ID
	client, err = suite.service.FindClientByClientID("test_client_1")

	// Error should be nil
	assert.Nil(suite.T(), err)

	// Correct client object should be returned
	if assert.NotNil(suite.T(), client) {
		assert.Equal(suite.T(), "test_client_1", client.Key)
	}
}
Example #10
0
// Ensure that the store can delete a directory if recursive is specified.
func TestStoreDeleteDiretory(t *testing.T) {
	s := newStore()
	// create directory /foo
	s.Create("/foo", true, "", false, Permanent)
	// delete /foo with dir = true and recursive = false
	// this should succeed, since the directory is empty
	e, err := s.Delete("/foo", true, false)
	assert.Nil(t, err, "")
	assert.Equal(t, e.Action, "delete", "")
	// check pervNode
	assert.NotNil(t, e.PrevNode, "")
	assert.Equal(t, e.PrevNode.Key, "/foo", "")
	assert.Equal(t, e.PrevNode.Dir, true, "")

	// create directory /foo and directory /foo/bar
	s.Create("/foo/bar", true, "", false, Permanent)
	// delete /foo with dir = true and recursive = false
	// this should fail, since the directory is not empty
	_, err = s.Delete("/foo", true, false)
	assert.NotNil(t, err, "")

	// delete /foo with dir=false and recursive = true
	// this should succeed, since recursive implies dir=true
	// and recursively delete should be able to delete all
	// items under the given directory
	e, err = s.Delete("/foo", false, true)
	assert.Nil(t, err, "")
	assert.Equal(t, e.Action, "delete", "")

}
Example #11
0
func TestNewHydre(t *testing.T) {
	h, err := NewHydre("test/good-conf.yml")
	assert.Nil(t, err)
	assert.Equal(t, 10, h.Timeout)
	assert.Len(t, h.Daemons, 2)
	assert.Contains(t, h.Daemons, &Daemon{
		Name:        "daemon1",
		Command:     []string{"start", "daemon1"},
		StopCommand: []string{"stop", "daemon1"},
		PidFile:     "path/to/pidfile",
		LogFiles:    []string{"1.log", "2.log"},
	})
	assert.Contains(t, h.Daemons, &Daemon{
		Name:    "daemon2",
		Command: []string{"start", "daemon2"},
	})

	h, err = NewHydre("test/bad-conf.yml")
	assert.NotNil(t, err)
	assert.Nil(t, h)

	h, err = NewHydre("does-not-exist.yml")
	assert.NotNil(t, err)
	assert.Nil(t, h)
}
Example #12
0
func testSize(t *testing.T, size int) {
	var b bytes.Buffer
	text := string(bytes.Repeat([]byte("a"), size))
	payload := bytes.Repeat([]byte{1}, size)
	w := bufio.NewWriter(&b)
	err := WritePacket(w, &Packet{
		Text:    text,
		Seq:     1234,
		Payload: payload,
	})
	assert.Nil(t, err)
	// log.Println("size:", size)
	// for i := 0; i < len(b.Bytes()) && i < 255; i++ {
	// 	fmt.Printf("%02x ", b.Bytes()[i])
	// }
	// fmt.Println("")

	var pkt Packet
	r := bufio.NewReader(&b)
	err = ReadPacket(r, &pkt)
	assert.Nil(t, err)
	assert.EqualValues(t, len([]byte(text)), pkt.LengthText)
	assert.EqualValues(t, len(payload), pkt.LengthPayload)
	assert.EqualValues(t, 1234, pkt.Seq)
	assert.EqualValues(t, text, pkt.Text)
	assert.EqualValues(t, payload, pkt.Payload)
}
Example #13
0
func TestGetters(t *testing.T) {
	assert.False(t, IsAuthenticatedFromContext(context.Background()))
	_, err := PoliciesFromContext(context.Background())
	assert.NotNil(t, err)
	_, err = SubjectFromContext(context.Background())
	assert.NotNil(t, err)
	_, err = TokenFromContext(context.Background())
	assert.NotNil(t, err)

	ctx := context.Background()
	claims := hjwt.ClaimsCarrier{"sub": "peter"}
	token := &jwt.Token{Valid: true}
	policies := []policy.Policy{}
	ctx = NewContextFromAuthValues(ctx, claims, token, policies)

	assert.True(t, IsAuthenticatedFromContext(ctx))
	policiesContext, err := PoliciesFromContext(ctx)
	assert.Nil(t, err)
	assert.Equal(t, policies, policiesContext)

	subjectContext, err := SubjectFromContext(ctx)
	assert.Nil(t, err)
	assert.Equal(t, claims.GetSubject(), subjectContext)

	tokenContext, err := TokenFromContext(ctx)
	assert.Nil(t, err)
	assert.Equal(t, token, tokenContext)
}
func TestMaxTime(t *testing.T) {
	assert := assert.New(t)
	b, err := New(time.Millisecond*200, 100000, 100000, 10,
		func(str interface{}) uint {
			return uint(len(str.(string)))
		},
	)
	assert.Nil(err)

	go func() {
		for i := 0; i < 10000; i++ {
			b.Put("a")
			time.Sleep(time.Millisecond)
		}
	}()

	before := time.Now()
	batch, err := b.Get()

	// This delta is normally 1-3 ms but running tests in CI with -race causes
	// this to run much slower. For now, just bump up the threshold.
	assert.InDelta(200, time.Since(before).Seconds()*1000, 50)
	assert.True(len(batch) > 0)
	assert.Nil(err)
}
Example #15
0
func TestAmqp_RecoverMethod(t *testing.T) {
	if testing.Verbose() {
		logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"amqp", "amqpdetailed"})
	}

	amqp := amqpModForTests()
	amqp.sendRequest = true

	data, err := hex.DecodeString("01000100000005003c006e01ce")
	assert.Nil(t, err)
	data2, err := hex.DecodeString("01000100000004003c006fce")
	assert.Nil(t, err)

	tcptuple := testTCPTuple()

	req := protos.Packet{Payload: data}
	private := protos.ProtocolData(new(amqpPrivateData))
	private = amqp.Parse(&req, tcptuple, 0, private)
	req = protos.Packet{Payload: data2}
	amqp.Parse(&req, tcptuple, 1, private)

	trans := expectTransaction(t, amqp)
	assert.Equal(t, "basic.recover", trans["method"])
	assert.Equal(t, "basic.recover", trans["request"])
	assert.Equal(t, "amqp", trans["type"])
	assert.Equal(t, common.OK_STATUS, trans["status"])
	assert.Equal(t, common.MapStr{"requeue": true}, trans["amqp"])
}
func TestOutputService4ProtocolTestListsCase2(t *testing.T) {
	sess := session.New()
	svc := NewOutputService4ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})

	buf := bytes.NewReader([]byte("{\"ListMember\": [\"a\", null], \"ListMemberMap\": [{}, null, null, {}], \"ListMemberStruct\": [{}, null, null, {}]}"))
	req, out := svc.OutputService4TestCaseOperation2Request(nil)
	req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}

	// set headers

	// unmarshal response
	jsonrpc.UnmarshalMeta(req)
	jsonrpc.Unmarshal(req)
	assert.NoError(t, req.Error)

	// assert response
	assert.NotNil(t, out) // ensure out variable is used
	assert.Equal(t, "a", *out.ListMember[0])
	assert.Nil(t, out.ListMember[1])
	assert.Nil(t, out.ListMemberMap[1])
	assert.Nil(t, out.ListMemberMap[2])
	assert.Nil(t, out.ListMemberStruct[1])
	assert.Nil(t, out.ListMemberStruct[2])

}
Example #17
0
func TestValidClaimsContext(t *testing.T) {
	userClaims := ClaimsContext{"user-id": "123456", "custom-time": 1453066866, "custom-time-f": 1631.083, "custom-date": time.Date(2016, time.January, 17, 19, 00, 00, 00, &time.Location{})}
	ctx, err := NewClaimsContext("fosite/auth", "Peter", "*****@*****.**", "", time.Now().Add(time.Hour), time.Now(), time.Now(), userClaims)
	assert.Nil(t, err)

	assert.Equal(t, "fosite/auth", ctx.GetIssuer())
	assert.NotEqual(t, "fosite/token", ctx.GetIssuer())
	assert.Equal(t, "Peter", ctx.GetSubject())
	assert.NotEqual(t, "Alex", ctx.GetSubject())
	assert.Equal(t, "*****@*****.**", ctx.GetAudience())
	assert.NotEqual(t, "*****@*****.**", ctx.GetAudience())

	assert.Equal(t, time.Now().Day(), ctx.GetNotBefore().Day())
	assert.Equal(t, time.Now().Day(), ctx.GetIssuedAt().Day())
	assert.Equal(t, time.Now().Add(time.Hour).Day(), ctx.GetExpiresAt().Day())

	assert.Equal(t, time.Now().Add(time.Hour).Day(), ctx.GetAsTime("exp").Day())
	assert.Equal(t, time.Date(2016, time.January, 17, 19, 00, 00, 00, &time.Location{}), ctx.GetAsTime("custom-date"))
	assert.NotNil(t, ctx.GetAsTime("custom-time"))
	assert.NotNil(t, ctx.GetAsTime("custom-time-f"))

	str, err := ctx.String()
	assert.NotNil(t, str)
	assert.Nil(t, err)

	assert.Empty(t, ctx.GetAsString("doesnotexist"))
	assert.Equal(t, time.Time{}, ctx.GetAsTime("doesnotexist"))
	stringRep, err := ctx.String()
	assert.Nil(t, err)
	assert.NotEmpty(t, stringRep)
}
Example #18
0
func TestVersionOneCreateIndex(t *testing.T) {
	dir := createTestDir(t)

	// open index file
	indexfile := filepath.Join(dir, "test001.idx")

	// delete prior test file
	err := os.Remove(indexfile)
	if err != nil && !os.IsNotExist(err) {
		t.Error(err)
	}

	// create index factory
	index, err := VersionOneIndexFactory(indexfile, VersionOne, DefaultIndexFlags)

	assert.NotNil(t, index, "Index file could not be created")
	assert.Nil(t, err, "CreateIndex produced an error")

	// stat file header size
	info, err := os.Stat(indexfile)
	assert.Nil(t, err, "os.Stat call resulted in error")
	assert.Equal(t, 8, info.Size(), "Invalid header size")

	// test header
	header := index.Header()
	assert.Equal(t, 1, int(header.Version()))
	assert.Equal(t, uint32(DefaultIndexFlags), header.Flags())

	// test Size
	size := index.Size()
	assert.Equal(t, 0, int(size))
}
Example #19
0
func TestRotateFileNb(t *testing.T) {
	dir, err := ioutil.TempDir("", "testrotlog")
	if err != nil {
		fmt.Println("Failed to create test dir in TestIfFileExists, skipping...")
		return
	}
	r := new(Rotlog)
	r.nbFiles = 8
	r.filename = dir + "/test"
	_, err = r.createFileNb(0)
	if err != nil {
		fmt.Println("Failed to create test dir in TestIfFileExists, skipping...")
		return
	}
	assert.Equal(t, true, r.fileNumberExists(0))
	assert.Nil(t, r.rotateFileNb(0))
	assert.Equal(t, true, r.fileNumberExists(1))
	assert.Nil(t, r.rotateFileNb(1))
	assert.Equal(t, true, r.fileNumberExists(2))
	assert.NotNil(t, r.rotateFileNb(12))
	err = os.RemoveAll(dir)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
}
Example #20
0
func TestAmqp_ChannelCloseErrorMethod(t *testing.T) {
	if testing.Verbose() {
		logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"amqp", "amqpdetailed"})
	}

	amqp := amqpModForTests()

	data, err := hex.DecodeString("0100010000009000140028019685505245434f4e444" +
		"954494f4e5f4641494c4544202d20696e6571756976616c656e74206172672027617574" +
		"6f5f64656c6574652720666f722065786368616e676520277465737445786368616e676" +
		"52720696e2076686f737420272f273a207265636569766564202774727565272062757" +
		"42063757272656e74206973202766616c7365270028000ace")
	assert.Nil(t, err)
	data2, err := hex.DecodeString("0100010000000400280033ce")
	assert.Nil(t, err)

	tcptuple := testTCPTuple()

	req := protos.Packet{Payload: data}
	private := protos.ProtocolData(new(amqpPrivateData))
	private = amqp.Parse(&req, tcptuple, 0, private)
	req = protos.Packet{Payload: data2}
	amqp.Parse(&req, tcptuple, 1, private)

	trans := expectTransaction(t, amqp)
	assert.Equal(t, "channel.close", trans["method"])
	assert.Equal(t, "amqp", trans["type"])
	assert.Equal(t, common.ERROR_STATUS, trans["status"])
	assert.Nil(t, trans["notes"])
}
Example #21
0
func TestMultipleGetEmpty(t *testing.T) {
	q := New(10)
	var wg sync.WaitGroup
	wg.Add(2)
	results := make([][]interface{}, 2)

	go func() {
		wg.Done()
		local, err := q.Get(1)
		assert.Nil(t, err)
		results[0] = local
		wg.Done()
	}()

	go func() {
		wg.Done()
		local, err := q.Get(1)
		assert.Nil(t, err)
		results[1] = local
		wg.Done()
	}()

	wg.Wait()
	wg.Add(2)

	q.Put(`a`, `b`, `c`)
	wg.Wait()

	if assert.Len(t, results[0], 1) && assert.Len(t, results[1], 1) {
		assert.True(t, (results[0][0] == `a` && results[1][0] == `b`) ||
			(results[0][0] == `b` && results[1][0] == `a`),
			`The array should be a, b or b, a`)
	}
}
Example #22
0
func TestAmqp_ConnectionCloseNoError(t *testing.T) {
	if testing.Verbose() {
		logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"amqp", "amqpdetailed"})
	}

	amqp := amqpModForTests()
	amqp.hideConnectionInformation = false

	data, err := hex.DecodeString("01000000000012000a003200c8076b74687862616900000000ce")
	assert.Nil(t, err)
	data2, err := hex.DecodeString("01000000000004000a0033ce")
	assert.Nil(t, err)

	tcptuple := testTCPTuple()

	req := protos.Packet{Payload: data}
	private := protos.ProtocolData(new(amqpPrivateData))
	private = amqp.Parse(&req, tcptuple, 0, private)
	req = protos.Packet{Payload: data2}
	amqp.Parse(&req, tcptuple, 1, private)

	trans := expectTransaction(t, amqp)
	assert.Equal(t, "connection.close", trans["method"])
	assert.Equal(t, "amqp", trans["type"])
	assert.Equal(t, common.OK_STATUS, trans["status"])
	assert.Nil(t, trans["notes"])

	fields, ok := trans["amqp"].(common.MapStr)
	assert.True(t, ok)
	code, ok := fields["reply-code"].(uint16)
	assert.True(t, ok)
	assert.Equal(t, uint16(200), code)
}
Example #23
0
func TestSimpleEvent(t *testing.T) {
	transp := newMockTransport()
	client := newClientTestDriver(newLumberjackClient(transp, 5*time.Second))

	event := common.MapStr{"name": "me", "line": 10}
	client.Publish([]common.MapStr{event})

	// receive window message
	buf := streambuf.New(nil)
	win, err := recvMessage(buf, transp)
	assert.Nil(t, err)

	// receive data message
	msg, err := recvMessage(buf, transp)
	assert.Nil(t, err)

	// send ack
	sendAck(transp, 1)

	// stop test driver
	transp.Close()
	client.Stop()

	// validate
	assert.NotNil(t, win)
	assert.NotNil(t, msg)
	assert.Equal(t, 1, len(msg.events))
	msg = msg.events[0]
	assert.Equal(t, "me", msg.doc["name"])
	assert.Equal(t, 10.0, msg.doc["line"])
}
Example #24
0
func TestAmqp_MultipleBodyFrames(t *testing.T) {
	if testing.Verbose() {
		logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"amqp", "amqpdetailed"})
	}

	amqp := amqpModForTests()
	amqp.sendRequest = true
	data, err := hex.DecodeString("0100010000000e003c00280000000568656c6c6f00ce" +
		"02000100000021003c0000000000000000002a80400a746578742f706c61696e00000000" +
		"56a22873ce030001000000202a2a2a68656c6c6f2049206c696b6520746f207075626c69" +
		"736820626967206dce")
	assert.Nil(t, err)
	data2, err := hex.DecodeString("0300010000000a657373616765732a2a2ace")
	assert.Nil(t, err)

	tcptuple := testTCPTuple()
	req := protos.Packet{Payload: data}
	private := protos.ProtocolData(new(amqpPrivateData))
	private = amqp.Parse(&req, tcptuple, 0, private)
	req = protos.Packet{Payload: data2}
	amqp.Parse(&req, tcptuple, 0, private)
	trans := expectTransaction(t, amqp)
	assert.Equal(t, "basic.publish", trans["method"])
	assert.Equal(t, "***hello I like to publish big messages***", trans["request"])
}
func TestCompileFileNameRegex(t *testing.T) {
	configFilePath := path.Join("testdata", "json_objects", "bag_validation_config.json")
	conf, errors := validation.LoadBagValidationConfig(configFilePath)
	if errors != nil && len(errors) > 0 {
		assert.Fail(t, errors[0].Error())
	}
	err := conf.CompileFileNameRegex()
	assert.Nil(t, err)

	conf.FileNamePattern = "ThisPatternIsInvalid[-"
	err = conf.CompileFileNameRegex()
	require.NotNil(t, err)
	assert.True(t, strings.HasPrefix(err.Error(), "Cannot compile regex"))

	conf.FileNamePattern = "aptrust"
	err = conf.CompileFileNameRegex()
	assert.Nil(t, err)
	assert.Equal(t, constants.APTrustFileNamePattern, conf.FileNameRegex)

	conf.FileNamePattern = "APTRUST"
	err = conf.CompileFileNameRegex()
	assert.Nil(t, err)
	assert.Equal(t, constants.APTrustFileNamePattern, conf.FileNameRegex)

	conf.FileNamePattern = "posix"
	err = conf.CompileFileNameRegex()
	assert.Nil(t, err)
	assert.Equal(t, constants.PosixFileNamePattern, conf.FileNameRegex)

	conf.FileNamePattern = "POSIX"
	err = conf.CompileFileNameRegex()
	assert.Nil(t, err)
	assert.Equal(t, constants.PosixFileNamePattern, conf.FileNameRegex)

}
Example #26
0
func TestAmqp_GetEmptyMethod(t *testing.T) {
	if testing.Verbose() {
		logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"amqp", "amqpdetailed"})
	}

	amqp := amqpModForTests()
	amqp.sendRequest = true

	data, err := hex.DecodeString("01000100000013003c004600000b526f626269" +
		"654b65616e6501ce")
	assert.Nil(t, err)
	data2, err := hex.DecodeString("01000100000005003c004800ce")
	assert.Nil(t, err)

	tcptuple := testTCPTuple()

	req := protos.Packet{Payload: data}
	private := protos.ProtocolData(new(amqpPrivateData))
	private = amqp.Parse(&req, tcptuple, 0, private)
	req = protos.Packet{Payload: data2}
	amqp.Parse(&req, tcptuple, 1, private)

	trans := expectTransaction(t, amqp)
	assert.Equal(t, "basic.get-empty", trans["method"])
	assert.Equal(t, "basic.get RobbieKeane", trans["request"])
	assert.Equal(t, "amqp", trans["type"])
	assert.Equal(t, common.OK_STATUS, trans["status"])
}
Example #27
0
func TestMakePrivateConnections(t *testing.T) {
	d := newDefaultDaemon()
	defer shutdown(d)
	d.Pool.Config.DialTimeout = time.Hour
	addr := "192.168.1.198:43071"
	addrb := "192.168.1.197:43072"
	// Two privates
	p, err := d.Peers.Peers.AddPeer(addr)
	assert.Nil(t, err)
	p.Private = true
	p, err = d.Peers.Peers.AddPeer(addrb)
	assert.Nil(t, err)
	p.Private = true
	// Not private
	p, err = d.Peers.Peers.AddPeer(addrc)
	assert.Nil(t, err)
	p.Private = false

	// Disabled
	d.Config.DisableOutgoingConnections = true
	d.makePrivateConnections()
	assert.Equal(t, len(d.pendingConnections), 0)

	// Enabled
	d.Config.DisableOutgoingConnections = false
	d.makePrivateConnections()
	assert.Equal(t, len(d.pendingConnections), 2)
	assert.NotNil(t, d.pendingConnections[addr])
	assert.NotNil(t, d.pendingConnections[addrb])
	assert.Nil(t, d.pendingConnections[addrc])
}
Example #28
0
func TestAmqp_GetMethod(t *testing.T) {
	if testing.Verbose() {
		logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"amqp", "amqpdetailed"})
	}

	amqp := amqpModForTests()
	amqp.sendRequest = true
	amqp.sendResponse = true

	data, err := hex.DecodeString("0100010000000f003c0046000007546573744" +
		"7657401ce")
	assert.Nil(t, err)
	data2, err := hex.DecodeString("0100010000001a003c00470000000000000001" +
		"0000075465737447657400000001ce02000100000019003c000000000000000000" +
		"1280000a746578742f706c61696ece03000100000012476574206d6520696620796" +
		"f752064617265ce")
	assert.Nil(t, err)

	tcptuple := testTCPTuple()

	req := protos.Packet{Payload: data}
	private := protos.ProtocolData(new(amqpPrivateData))
	private = amqp.Parse(&req, tcptuple, 0, private)
	req = protos.Packet{Payload: data2}
	amqp.Parse(&req, tcptuple, 1, private)

	trans := expectTransaction(t, amqp)
	assert.Equal(t, "basic.get", trans["method"])
	assert.Equal(t, "basic.get TestGet", trans["request"])
	assert.Equal(t, "amqp", trans["type"])
	assert.Equal(t, common.OK_STATUS, trans["status"])
	assert.Equal(t, "Get me if you dare", trans["response"])
}
func TestParseFederationReplicaSetReference(t *testing.T) {
	successPrefs := []string{
		`{"rebalance": true,
		  "clusters": {
		    "k8s-1": {"minReplicas": 10, "maxReplicas": 20, "weight": 2},
		    "*": {"weight": 1}
		}}`,
	}
	failedPrefes := []string{
		`{`, // bad json
	}

	rs := newReplicaSetWithReplicas("rs-1", 100)
	accessor, _ := meta.Accessor(rs)
	anno := accessor.GetAnnotations()
	if anno == nil {
		anno = make(map[string]string)
		accessor.SetAnnotations(anno)
	}
	for _, prefString := range successPrefs {
		anno[FedReplicaSetPreferencesAnnotation] = prefString
		pref, err := parseFederationReplicaSetReference(rs)
		assert.NotNil(t, pref)
		assert.Nil(t, err)
	}
	for _, prefString := range failedPrefes {
		anno[FedReplicaSetPreferencesAnnotation] = prefString
		pref, err := parseFederationReplicaSetReference(rs)
		assert.Nil(t, pref)
		assert.NotNil(t, err)
	}
}
func TestMultiConsumer(t *testing.T) {
	assert := assert.New(t)
	b, err := New(0, 100, 100000, 10, func(str interface{}) uint {
		return uint(len(str.(string)))
	})
	assert.Nil(err)

	var wg sync.WaitGroup
	wg.Add(5)
	for i := 0; i < 5; i++ {
		go func() {
			batch, err := b.Get()
			assert.Len(batch, 100)
			assert.Nil(err)
			wg.Done()
		}()
	}

	go func() {
		for i := 0; i < 500; i++ {
			b.Put("a")
		}
	}()

	wg.Wait()
}