Esempio n. 1
0
func TestCentosSetUserPassword(t *testing.T) {
	deps, centos := buildCentos()

	centos.SetUserPassword("my-user", "my-encrypted-password")
	assert.Equal(t, 1, len(deps.cmdRunner.RunCommands))
	assert.Equal(t, []string{"usermod", "-p", "my-encrypted-password", "my-user"}, deps.cmdRunner.RunCommands[0])
}
Esempio n. 2
0
func TestSearchService_Code(t *testing.T) {
	setup()
	defer tearDown()

	stubGet(t, "/search/code", "code_search", nil)

	searchResults, result := client.Search().Code(nil, M{
		"query": "addClass in:file language:js repo:jquery/jquery"})

	assert.False(t, result.HasError())
	assert.False(t, searchResults.IncompleteResults)
	assert.Equal(t, 7, searchResults.TotalCount)
	assert.Equal(t, 7, len(searchResults.Items))
	assert.EqualValues(t, "classes.js", searchResults.Items[0].Name)
	assert.EqualValues(t, "src/attributes/classes.js", searchResults.Items[0].Path)
	assert.EqualValues(t,
		"f9dba94f7de43d6b6b7256e05e0d17c4741a4cde", searchResults.Items[0].SHA)
	assert.EqualValues(t,
		"https://api.github.com/repositories/167174/contents/src/attributes/classes.js?ref=53aa87f3bf4284763405f3eb8affff296e55ba4f", string(searchResults.Items[0].URL))
	assert.EqualValues(t,
		"https://api.github.com/repositories/167174/git/blobs/f9dba94f7de43d6b6b7256e05e0d17c4741a4cde", searchResults.Items[0].GitURL)
	assert.EqualValues(t,
		"https://github.com/jquery/jquery/blob/53aa87f3bf4284763405f3eb8affff296e55ba4f/src/attributes/classes.js", searchResults.Items[0].HTMLURL)
	assert.Equal(t, 167174, searchResults.Items[0].Repository.ID)
	assert.EqualValues(t,
		"jquery/jquery", searchResults.Items[0].Repository.FullName)
}
Esempio n. 3
0
File: id_test.go Progetto: rs/xid
func TestNew(t *testing.T) {
	// Generate 10 ids
	ids := make([]ID, 10)
	for i := 0; i < 10; i++ {
		ids[i] = New()
	}
	for i := 1; i < 10; i++ {
		prevID := ids[i-1]
		id := ids[i]
		// Test for uniqueness among all other 9 generated ids
		for j, tid := range ids {
			if j != i {
				assert.NotEqual(t, id, tid, "Generated ID is not unique")
			}
		}
		// Check that timestamp was incremented and is within 30 seconds of the previous one
		secs := id.Time().Sub(prevID.Time()).Seconds()
		assert.Equal(t, (secs >= 0 && secs <= 30), true, "Wrong timestamp in generated ID")
		// Check that machine ids are the same
		assert.Equal(t, id.Machine(), prevID.Machine())
		// Check that pids are the same
		assert.Equal(t, id.Pid(), prevID.Pid())
		// Test for proper increment
		delta := int(id.Counter() - prevID.Counter())
		assert.Equal(t, delta, 1, "Wrong increment in generated ID")
	}
}
Esempio n. 4
0
func TestCullInvalidConnections(t *testing.T) {
	d := newDefaultDaemon()
	// Is fine
	d.ExpectingIntroductions[addr] = time.Now()
	// Is expired
	d.ExpectingIntroductions[addrb] = util.ZeroTime()
	// Is not in pool
	d.ExpectingIntroductions[addrc] = util.ZeroTime()
	d.Peers.Peers.AddPeer(addr)
	d.Peers.Peers.AddPeer(addrb)
	d.Peers.Peers.AddPeer(addrc)
	d.Pool.Pool.Addresses[addr] = gnetConnection(addr)
	d.Pool.Pool.Addresses[addrb] = gnetConnection(addrb)
	d.Pool.Pool.Addresses[addrb].Id = 2
	d.Pool.Pool.Pool[1] = d.Pool.Pool.Addresses[addr]
	d.Pool.Pool.Pool[2] = d.Pool.Pool.Addresses[addrb]

	assert.NotPanics(t, d.cullInvalidConnections)

	assert.Equal(t, len(d.ExpectingIntroductions), 1)
	assert.Equal(t, len(d.Peers.Peers.Peerlist), 2)
	assert.Equal(t, len(d.Pool.Pool.DisconnectQueue), 1)
	if len(d.Pool.Pool.DisconnectQueue) == 0 {
		t.Fatal("pool.Pool.DisconnectQueue not empty, would block")
	}
	de := <-d.Pool.Pool.DisconnectQueue
	assert.Equal(t, de.ConnId, 2)
	assert.Equal(t, de.Reason, DisconnectIntroductionTimeout)
	shutdown(d)
}
Esempio n. 5
0
// TestFormIsValid tests data that come from request (url.Values)
func TestFormIsValid(t *testing.T) {
	postData := url.Values{
		"field1": []string{"Foo"},
		"field2": []string{"Bar"},
		"fieldX": []string{"Ham"},
	}

	f := Form{
		Fields: map[string]*Field{
			"field1": &Field{
				Type: &Input{},
			},
			"field2": &Field{
				Type: &Input{},
			},
		},
	}

	assert.Equal(
		t, f.CleanedData, *new(Data),
		"CleanedData should be empty at beggining")

	assert.True(t, f.IsValid(postData), "Form should pass")
	assert.Equal(
		t, f.CleanedData, Data{"field1": "Foo", "field2": "Bar"},
		"Forms CleanedData field should contain cleaned data")

	assert.True(t, f.IsValid(url.Values{}), "Form should pass")
	assert.Equal(
		t, f.CleanedData, Data{"field1": "", "field2": ""},
		"Form should pass")
}
Esempio n. 6
0
func TestServiceSummaryGetSummariesInCurrentSpace(t *testing.T) {
	req := testapi.NewCloudControllerTestRequest(testnet.TestRequest{
		Method:   "GET",
		Path:     "/v2/spaces/my-space-guid/summary",
		Response: serviceInstanceSummariesResponse,
	})

	ts, handler, repo := createServiceSummaryRepo(t, req)
	defer ts.Close()

	serviceInstances, apiResponse := repo.GetSummariesInCurrentSpace()
	assert.True(t, handler.AllRequestsCalled())

	assert.True(t, apiResponse.IsSuccessful())
	assert.Equal(t, 1, len(serviceInstances))

	instance1 := serviceInstances[0]
	assert.Equal(t, instance1.Name, "my-service-instance")
	assert.Equal(t, instance1.ServicePlan.Name, "spark")
	assert.Equal(t, instance1.ServiceOffering.Label, "cleardb")
	assert.Equal(t, instance1.ServiceOffering.Label, "cleardb")
	assert.Equal(t, instance1.ServiceOffering.Provider, "cleardb-provider")
	assert.Equal(t, instance1.ServiceOffering.Version, "n/a")
	assert.Equal(t, len(instance1.ApplicationNames), 2)
	assert.Equal(t, instance1.ApplicationNames[0], "app1")
	assert.Equal(t, instance1.ApplicationNames[1], "app2")
}
Esempio n. 7
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])
}
Esempio n. 8
0
func TestOutputService9ProtocolTestSupportsHeaderMapsCase1(t *testing.T) {
	svc := NewOutputService9ProtocolTest(nil)

	buf := bytes.NewReader([]byte("{}"))
	req, out := svc.OutputService9TestCaseOperation1Request(nil)
	req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}

	// set headers
	req.HTTPResponse.Header.Set("Content-Length", "10")
	req.HTTPResponse.Header.Set("X-Bam", "boo")
	req.HTTPResponse.Header.Set("X-Foo", "bar")

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

	// assert response
	assert.NotNil(t, out) // ensure out variable is used
	assert.Equal(t, "10", *out.AllHeaders["Content-Length"])
	assert.Equal(t, "boo", *out.AllHeaders["X-Bam"])
	assert.Equal(t, "bar", *out.AllHeaders["X-Foo"])
	assert.Equal(t, "boo", *out.PrefixedHeaders["Bam"])
	assert.Equal(t, "bar", *out.PrefixedHeaders["Foo"])

}
Esempio n. 9
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"])
}
Esempio n. 10
0
func TestFilterFlags(t *testing.T) {
	result := filterFlags("text/html ")
	assert.Equal(t, result, "text/html")

	result = filterFlags("text/html;")
	assert.Equal(t, result, "text/html")
}
Esempio n. 11
0
func TestAddRoute(t *testing.T) {
	node1, node2 := NewNode(), NewNode()
	assert.Len(t, node1.RouteForwardingRules, 0, "Should be 0 routes")

	ccid := node1.AddControlChannel()
	node1.Tick() // run channels consuming

	tf := transport.NewTransportFactory()
	tf.ConnectNodeToNode(node1, node2)
	tr1, _ := tf.GetTransports()
	tid1 := tr1.Id

	incomingRouteId := messages.RandRouteId()
	outgoingRouteId := messages.RandRouteId()

	msg := messages.AddRouteControlMessage{
		(messages.TransportId)(0),
		tr1.Id,
		incomingRouteId,
		outgoingRouteId,
	}
	msgS := messages.Serialize(messages.MsgAddRouteControlMessage, msg)

	controlMessage := messages.InControlMessage{ccid, msgS}

	node1.InjectControlMessage(controlMessage)
	time.Sleep(1 * time.Millisecond)

	assert.Len(t, node1.RouteForwardingRules, 1, "Should be 1 routes")
	assert.Equal(t, node1.RouteForwardingRules[incomingRouteId].IncomingRoute, incomingRouteId)
	assert.Equal(t, node1.RouteForwardingRules[incomingRouteId].OutgoingRoute, outgoingRouteId)
	assert.Equal(t, node1.RouteForwardingRules[incomingRouteId].OutgoingTransport, tid1)

	fmt.Println("--------------------\n")
}
Esempio n. 12
0
func TestChooseData(t *testing.T) {
	A := "a"
	B := "b"
	assert.Equal(t, chooseData(A, B), A)
	assert.Equal(t, chooseData(nil, B), B)
	assert.Panics(t, func() { chooseData(nil, nil) })
}
Esempio n. 13
0
func assertRequestIsProcessedSynchronously(t *testing.T, req boshmbus.Request) {
	settings, handler, platform, taskService, actionFactory := getAgentDependencies()

	// when action is successful
	actionFactory.CreateAction = &fakeaction.TestAction{
		RunValue: "some value",
	}

	agent := New(settings, handler, platform, taskService, actionFactory)

	err := agent.Run()
	assert.NoError(t, err)
	assert.True(t, handler.ReceivedRun)

	resp := handler.Func(req)
	assert.Equal(t, req.Method, actionFactory.CreateMethod)
	assert.Equal(t, req.GetPayload(), actionFactory.CreateAction.RunPayload)
	assert.Equal(t, boshmbus.NewValueResponse("some value"), resp)

	// when action returns an error
	actionFactory.CreateAction = &fakeaction.TestAction{
		RunErr: errors.New("some error"),
	}

	agent = New(settings, handler, platform, taskService, actionFactory)
	agent.Run()

	resp = handler.Func(req)
	boshassert.MatchesJsonString(t, resp, `{"exception":{"message":"some error"}}`)
}
Esempio n. 14
0
func TestCentosSetupDhcp(t *testing.T) {
	deps, centos := buildCentos()
	testCentosSetupDhcp(t, deps, centos)

	assert.Equal(t, len(deps.cmdRunner.RunCommands), 1)
	assert.Equal(t, deps.cmdRunner.RunCommands[0], []string{"service", "network", "restart"})
}
Esempio n. 15
0
func testStateTrace(t *testing.T, transitions []transition) *Registry {
	assert := assert.New(t)

	registry := NewInMemoryRegistry()
	a, _ := fakePodTask("a")
	a, _ = registry.Register(a, nil)

	// initial pending state
	assert.Equal(a.State, StatePending)

	for _, transition := range transitions {
		if transition.expectPanic {
			assert.Panics(func() {
				registry.UpdateStatus(fakeStatusUpdate(a.ID, transition.statusUpdate))
			})
		} else {
			a, _ = registry.UpdateStatus(fakeStatusUpdate(a.ID, transition.statusUpdate))
			if transition.expectedState == nil {
				a, _ = registry.Get(a.ID)
				assert.Nil(a, "expected task to be deleted from registry after status update to %v", transition.statusUpdate)
			} else {
				assert.Equal(a.State, *transition.expectedState)
			}
		}
	}

	return &registry
}
Esempio n. 16
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)
}
Esempio n. 17
0
func TestRead(t *testing.T) {
	assert := assert.New(t)
	ds := datas.NewDataStore(chunks.NewMemoryStore())

	dataString := `a,1,true
b,2,false
`
	r := NewCSVReader(bytes.NewBufferString(dataString), ',')

	headers := []string{"A", "B", "C"}
	kinds := KindSlice{types.StringKind, types.Int8Kind, types.BoolKind}
	l, typeRef, typeDef := Read(r, "test", headers, kinds, ds)

	assert.Equal(uint64(2), l.Len())

	assert.True(typeRef.IsUnresolved())

	desc, ok := typeDef.Desc.(types.StructDesc)
	assert.True(ok)
	assert.Len(desc.Fields, 3)
	assert.Equal("A", desc.Fields[0].Name)
	assert.Equal("B", desc.Fields[1].Name)
	assert.Equal("C", desc.Fields[2].Name)

	assert.True(l.Get(0).(types.Struct).Get("A").Equals(types.NewString("a")))
	assert.True(l.Get(1).(types.Struct).Get("A").Equals(types.NewString("b")))

	assert.True(l.Get(0).(types.Struct).Get("B").Equals(types.Int8(1)))
	assert.True(l.Get(1).(types.Struct).Get("B").Equals(types.Int8(2)))

	assert.True(l.Get(0).(types.Struct).Get("C").Equals(types.Bool(true)))
	assert.True(l.Get(1).(types.Struct).Get("C").Equals(types.Bool(false)))
}
Esempio n. 18
0
func TestBlobLen(t *testing.T) {
	assert := assert.New(t)
	b := NewBlob(&bytes.Buffer{})
	assert.Equal(uint64(0), b.Len())
	b = NewBlob(bytes.NewBuffer([]byte{0x01}))
	assert.Equal(uint64(1), b.Len())
}
Esempio n. 19
0
func TestSendPings(t *testing.T) {
	d := newDefaultDaemon()
	defer shutdown(d)
	c := gnetConnection(addr)
	go d.Pool.Pool.ConnectionWriteLoop(c)
	d.Pool.Pool.Pool[1] = c
	assert.NotPanics(t, d.Pool.sendPings)
	wait()
	assert.Equal(t, len(d.Pool.Pool.SendResults), 1)
	if len(d.Pool.Pool.SendResults) == 0 {
		t.Fatal("SendResults empty, would block")
	}
	sr := <-d.Pool.Pool.SendResults
	assert.Equal(t, sr.Connection, c)
	assert.Nil(t, sr.Error)
	_, ok := sr.Message.(*PingMessage)
	assert.True(t, ok)
	assert.False(t, c.LastSent.IsZero())

	// No pings should be sent, since we just pinged
	lastSent := c.LastSent
	assert.NotPanics(t, d.Pool.sendPings)
	wait()
	assert.Equal(t, len(d.Pool.Pool.SendResults), 0)
	assert.Equal(t, c.LastSent, lastSent)
}
Esempio n. 20
0
func TestUpdateUser(t *testing.T) {
	assert := assert.New(t)
	s := sw.NewUserApi()
	newUser := sw.User{
		Id:         1000,
		FirstName:  "gopher20",
		LastName:   "lang20",
		Username:   "******",
		Password:   "******",
		Email:      "*****@*****.**",
		Phone:      "5101112222",
		UserStatus: 1}

	apiResponse, err := s.UpdateUser("gopher", newUser)

	if err != nil {
		t.Errorf("Error while deleting user by id")
		t.Log(err)
	}
	if apiResponse.Response.StatusCode != 200 {
		t.Log(apiResponse.Response)
	}

	//verify changings are correct
	resp, apiResponse, err := s.GetUserByName("gopher")
	if err != nil {
		t.Errorf("Error while getting user by id")
		t.Log(err)
	} else {
		assert.Equal(resp.Id, int64(1000), "User id should be equal")
		assert.Equal(resp.FirstName, "gopher20", "User name should be gopher")
		assert.Equal(resp.Password, "lang", "User name should be the same")
	}
}
Esempio n. 21
0
func TestConnectToRandomPeer(t *testing.T) {
	d := newDefaultDaemon()
	defer shutdown(d)
	defer cleanupPeers()

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

	// Enabled, but only private peers
	addr := "192.168.1.196:30954"
	p, err := d.Peers.Peers.AddPeer(addr)
	assert.Nil(t, err)
	p.Private = true
	d.Config.DisableOutgoingConnections = false
	assert.NotPanics(t, d.connectToRandomPeer)
	assert.Equal(t, len(d.pendingConnections), 0)

	// Enabled, and we have a public peer
	p.Private = false
	assert.NotPanics(t, d.connectToRandomPeer)
	assert.Equal(t, len(d.pendingConnections), 1)
	assert.NotNil(t, d.pendingConnections[addr])
}
Esempio n. 22
0
// TestInstallSwaggerAPI verifies that the swagger api is added
// at the proper endpoint.
func TestInstallSwaggerAPI(t *testing.T) {
	etcdserver, _, assert := setUp(t)
	defer etcdserver.Terminate(t)

	mux := http.NewServeMux()
	server := &GenericAPIServer{}
	server.HandlerContainer = NewHandlerContainer(mux, nil)

	// Ensure swagger isn't installed without the call
	ws := server.HandlerContainer.RegisteredWebServices()
	if !assert.Equal(len(ws), 0) {
		for x := range ws {
			assert.NotEqual("/swaggerapi", ws[x].RootPath(), "SwaggerAPI was installed without a call to InstallSwaggerAPI()")
		}
	}

	// Install swagger and test
	server.InstallSwaggerAPI()
	ws = server.HandlerContainer.RegisteredWebServices()
	if assert.NotEqual(0, len(ws), "SwaggerAPI not installed.") {
		assert.Equal("/swaggerapi/", ws[0].RootPath(), "SwaggerAPI did not install to the proper path. %s != /swaggerapi", ws[0].RootPath())
	}

	// Empty externalHost verification
	mux = http.NewServeMux()
	server.HandlerContainer = NewHandlerContainer(mux, nil)
	server.ExternalAddress = ""
	server.ClusterIP = net.IPv4(10, 10, 10, 10)
	server.PublicReadWritePort = 1010
	server.InstallSwaggerAPI()
	if assert.NotEqual(0, len(ws), "SwaggerAPI not installed.") {
		assert.Equal("/swaggerapi/", ws[0].RootPath(), "SwaggerAPI did not install to the proper path. %s != /swaggerapi", ws[0].RootPath())
	}
}
Esempio n. 23
0
func (suite *IntegrationMigrateSuite) TestMigrateDown() {
	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)

	down := NewDown(suite.Target)
	err = down.Migrate()
	assert.Nil(suite.T(), err)
	assert.Equal(suite.T(), up.Migrations.Len()-1, down.Migrations.Len())

	upFirst, err := up.Migrations.First()
	assert.Nil(suite.T(), err)
	downFirst, err := down.Migrations.First()
	assert.Nil(suite.T(), err)
	assert.Equal(suite.T(), upFirst.Id, downFirst.Id)

	upLast, err := up.Migrations.Last()
	assert.Nil(suite.T(), err)
	downLast, err := down.Migrations.Last()
	assert.Nil(suite.T(), err)
	assert.NotEqual(suite.T(), upLast.Id, downLast.Id)
}
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)

}
Esempio n. 25
0
// TestFromIsValidMap tests data that come from map
func TestFromIsValidMap(t *testing.T) {
	f := Form{
		Fields: map[string]*Field{
			"field1": &Field{
				Type: &Input{},
			},
			"field2": &Field{
				Type: &Input{},
			},
		},
	}

	values := map[string]interface{}{
		"field1": "Spam",
		"field2": []string{"Ham"},
	}

	assert.True(t, f.IsValidMap(values), "Form should pass")
	assert.Equal(
		t, f.CleanedData, Data{"field1": "Spam", "field2": "Ham"},
		"Form should pass")

	values = map[string]interface{}{
		"field1": "Spam",
	}

	assert.True(t, f.IsValidMap(values), "Form should pass")
	assert.Equal(
		t, f.CleanedData, Data{"field1": "Spam", "field2": ""},
		"Form should pass")
}
func TestLoadBagValidationConfig(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())
	}
	assert.True(t, conf.AllowMiscTopLevelFiles)
	assert.True(t, conf.AllowMiscDirectories)
	assert.True(t, conf.TopLevelDirMustMatchBagName)
	assert.Equal(t, 7, len(conf.FileSpecs))
	assert.Equal(t, 3, len(conf.TagSpecs))
	assert.Equal(t, 2, len(conf.FixityAlgorithms))

	// Spot checks
	if _, ok := conf.FileSpecs["manifest-md5.txt"]; !ok {
		assert.Fail(t, "FileSpec for manifest-md5.txt is missing")
	}
	if _, ok := conf.FileSpecs["manifest-sha256.txt"]; !ok {
		assert.Fail(t, "FileSpec for manifest-sha256.txt is missing")
	}
	if _, ok := conf.TagSpecs["Title"]; !ok {
		assert.Fail(t, "TagSpec for Title is missing")
	}
	if len(conf.FixityAlgorithms) > 1 {
		assert.Equal(t, "md5", conf.FixityAlgorithms[0])
		assert.Equal(t, "sha256", conf.FixityAlgorithms[1])
	}
	assert.Equal(t, validation.REQUIRED, conf.FileSpecs["manifest-md5.txt"].Presence)
	assert.Equal(t, validation.OPTIONAL, conf.FileSpecs["manifest-sha256.txt"].Presence)
	assert.Equal(t, "aptrust-info.txt", conf.TagSpecs["Title"].FilePath)
	assert.Equal(t, validation.REQUIRED, conf.TagSpecs["Title"].Presence)
	assert.False(t, conf.TagSpecs["Title"].EmptyOK)
	assert.Equal(t, 3, len(conf.TagSpecs["Access"].AllowedValues))
}
Esempio n. 27
0
func TestConfig_LoadSingleInput(t *testing.T) {
	c := NewConfig()
	c.LoadConfig("./testdata/single_plugin.toml")

	memcached := inputs.Inputs["memcached"]().(*memcached.Memcached)
	memcached.Servers = []string{"localhost"}

	mConfig := &InputConfig{
		Name: "memcached",
		Filter: Filter{
			Drop: []string{"other", "stuff"},
			Pass: []string{"some", "strings"},
			TagDrop: []TagFilter{
				TagFilter{
					Name:   "badtag",
					Filter: []string{"othertag"},
				},
			},
			TagPass: []TagFilter{
				TagFilter{
					Name:   "goodtag",
					Filter: []string{"mytag"},
				},
			},
			IsActive: true,
		},
		Interval: 5 * time.Second,
	}
	mConfig.Tags = make(map[string]string)

	assert.Equal(t, memcached, c.Inputs[0].Input,
		"Testdata did not produce a correct memcached struct.")
	assert.Equal(t, mConfig, c.Inputs[0].Config,
		"Testdata did not produce correct memcached metadata.")
}
Esempio n. 28
0
// TestGetNodeAddresses verifies that proper results are returned
// when requesting node addresses.
func TestGetNodeAddresses(t *testing.T) {
	assert := assert.New(t)

	fakeNodeClient := fake.NewSimpleClientset(registrytest.MakeNodeList([]string{"node1", "node2"}, api.NodeResources{})).Core().Nodes()
	addressProvider := nodeAddressProvider{fakeNodeClient}

	// Fail case (no addresses associated with nodes)
	nodes, _ := fakeNodeClient.List(api.ListOptions{})
	addrs, err := addressProvider.externalAddresses()

	assert.Error(err, "addresses should have caused an error as there are no addresses.")
	assert.Equal([]string(nil), addrs)

	// Pass case with External type IP
	nodes, _ = fakeNodeClient.List(api.ListOptions{})
	for index := range nodes.Items {
		nodes.Items[index].Status.Addresses = []api.NodeAddress{{Type: api.NodeExternalIP, Address: "127.0.0.1"}}
		fakeNodeClient.Update(&nodes.Items[index])
	}
	addrs, err = addressProvider.externalAddresses()
	assert.NoError(err, "addresses should not have returned an error.")
	assert.Equal([]string{"127.0.0.1", "127.0.0.1"}, addrs)

	// Pass case with LegacyHost type IP
	nodes, _ = fakeNodeClient.List(api.ListOptions{})
	for index := range nodes.Items {
		nodes.Items[index].Status.Addresses = []api.NodeAddress{{Type: api.NodeLegacyHostIP, Address: "127.0.0.2"}}
		fakeNodeClient.Update(&nodes.Items[index])
	}
	addrs, err = addressProvider.externalAddresses()
	assert.NoError(err, "addresses failback should not have returned an error.")
	assert.Equal([]string{"127.0.0.2", "127.0.0.2"}, addrs)
}
Esempio n. 29
0
func TestGetAccount(t *testing.T) {
	_, teardown, err := setup(t)
	if err != nil {
		t.Fatal(err)
	}

	defer teardown()

	// new account
	a := account.New()
	account.Set(a)

	act, err := account.Get(a.Pubkey)
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, act, a)

	// add wallet id
	act.WltIDs[bitcoin.Type] = "bitcoin_sd19"
	act.WltIDs[skycoin.Type] = "skycoin_sd19"
	account.Set(act)

	newA, err := account.Get(act.Pubkey)
	if err != nil {
		t.Fatal(err)
	}

	assert.Equal(t, newA, act)
}
Esempio n. 30
0
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])
}