Ejemplo n.º 1
0
// Test SessionLogin
func TestSessionLogin(t *testing.T) {
	var (
		c *ICSPClient
	)
	if os.Getenv("ICSP_TEST_ACCEPTANCE") == "true" {
		_, c = getTestDriverA()
		if c == nil {
			t.Fatalf("Failed to execute getTestDriver() ")
		}
		data, err := c.SessionLogin()
		// fmt.Printf("after SessionLogin: %s -> (err) %+v", data.ID, err)
		assert.NoError(t, err, "SessionLogin threw error -> %s", err)
		assert.NotEmpty(t, data.ID, fmt.Sprintf("SessionLogin is empty! something went wrong, err -> %s, data -> %+v\n", err, data))
		assert.Equal(t, "none", c.APIKey)

		c.APIKey = data.ID
		err = c.SessionLogout()
		assert.NoError(t, err, "SessionLogout threw error -> %s", err)
		data, err = c.SessionLogin()
		assert.NoError(t, err, "SessionLogin threw error -> %s", err)
	} else {
		_, c = getTestDriverU()
		data, err := c.SessionLogin()
		assert.Error(t, err, fmt.Sprintf("ALL ok, no error, caught as expected: %s,%+v\n", err, data))
		assert.Equal(t, "none", c.APIKey)
	}
}
Ejemplo n.º 2
0
func TestTypeResolver_AdditionalItems(t *testing.T) {
	_, resolver, err := basicTaskListResolver(t)
	tpe := spec.StringProperty()
	if assert.NoError(t, err) {
		// arrays of primitives and string formats with additional formats
		for _, val := range schTypeVals {
			var sch spec.Schema
			sch.Typed(val.Type, val.Format)
			var coll spec.Schema
			coll.Type = []string{"array"}
			coll.Items = new(spec.SchemaOrArray)
			coll.Items.Schema = tpe
			coll.AdditionalItems = new(spec.SchemaOrBool)
			coll.AdditionalItems.Schema = &sch

			rt, err := resolver.ResolveSchema(&coll, true)
			if assert.NoError(t, err) && assert.True(t, rt.IsArray) {
				assert.True(t, rt.HasAdditionalItems)
				assert.False(t, rt.IsNullable)
				//if assert.NotNil(t, rt.ElementType) {
				//assertPrimitiveResolve(t, "string", "", "string", *rt.ElementType)
				//}
			}
		}
	}
}
Ejemplo n.º 3
0
func testAtomicPut(t *testing.T, kv store.Store) {
	key := "testAtomicPut"
	value := []byte("world")

	// Put the key
	err := kv.Put(key, value, nil)
	assert.NoError(t, err)

	// Get should return the value and an incremented index
	pair, err := kv.Get(key)
	assert.NoError(t, err)
	if assert.NotNil(t, pair) {
		assert.NotNil(t, pair.Value)
	}
	assert.Equal(t, pair.Value, value)
	assert.NotEqual(t, pair.LastIndex, 0)

	// This CAS should fail: previous exists.
	success, _, err := kv.AtomicPut(key, []byte("WORLD"), nil, nil)
	assert.Error(t, err)
	assert.False(t, success)

	// This CAS should succeed
	success, _, err = kv.AtomicPut(key, []byte("WORLD"), pair, nil)
	assert.NoError(t, err)
	assert.True(t, success)

	// This CAS should fail, key exists.
	pair.LastIndex = 6744
	success, _, err = kv.AtomicPut(key, []byte("WORLDWORLD"), pair, nil)
	assert.Error(t, err)
	assert.False(t, success)
}
func TestCollect(t *testing.T) {
	cm := &collectorManager{}

	firstTime := time.Now().Add(-time.Hour)
	secondTime := time.Now().Add(time.Hour)
	f1 := &fakeCollector{
		nextCollectionTime: firstTime,
	}
	f2 := &fakeCollector{
		nextCollectionTime: secondTime,
	}

	assert := assert.New(t)
	assert.NoError(cm.RegisterCollector(f1))
	assert.NoError(cm.RegisterCollector(f2))

	// First collection, everyone gets collected from.
	nextTime, _, err := cm.Collect()
	assert.Equal(firstTime, nextTime)
	assert.NoError(err)
	assert.Equal(1, f1.collectedFrom)
	assert.Equal(1, f2.collectedFrom)

	f1.nextCollectionTime = time.Now().Add(2 * time.Hour)

	// Second collection, only the one that is ready gets collected from.
	nextTime, _, err = cm.Collect()
	assert.Equal(secondTime, nextTime)
	assert.NoError(err)
	assert.Equal(2, f1.collectedFrom)
	assert.Equal(1, f2.collectedFrom)
}
Ejemplo n.º 5
0
func TestDNSProvider_Present(t *testing.T) {
	os.Setenv("LINODE_API_KEY", "testing")
	defer restoreEnv()
	p, err := NewDNSProvider()
	assert.NoError(t, err)

	domain := "example.com"
	keyAuth := "dGVzdGluZw=="
	mockResponses := MockResponseMap{
		"domain.list": MockResponse{
			Response: []dns.Domain{
				dns.Domain{
					Domain:   domain,
					DomainID: 1234,
				},
			},
		},
		"domain.resource.create": MockResponse{
			Response: dns.ResourceResponse{
				ResourceID: 1234,
			},
		},
	}
	mockSrv := newMockServer(t, mockResponses)
	defer mockSrv.Close()
	p.linode.ToLinode().SetEndpoint(mockSrv.URL)

	err = p.Present(domain, "", keyAuth)
	assert.NoError(t, err)
}
Ejemplo n.º 6
0
func TestResurrectStmtSqlMockNoTicker(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
	}
	defer db.Close()

	mock.ExpectPrepare("INSERT INTO `xtable` \\(`path`,`value`\\) VALUES .+").
		ExpectExec().WithArgs("gopher", 3141).WillReturnResult(sqlmock.NewResult(1, 1))

	tw := newTypeWriterMocked(db)

	assert.NoError(t, tw.Save("gopher", 3141))
	assert.False(t, tw.Write.IsIdle())

	assert.NoError(t, tw.Write.StopIdleChecker())

	mock.ExpectPrepare("INSERT INTO `xtable` \\(`path`,`value`\\) VALUES .+").
		ExpectExec().WithArgs("gopher", 3144).WillReturnResult(sqlmock.NewResult(1, 1))

	assert.NoError(t, tw.Save("gopher", 3144))

	// we make sure that all expectations were met
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Errorf("there were unfulfilled expections: %s", err)
	}
}
Ejemplo n.º 7
0
func Test_Transport_FetchSpec(t *testing.T) {
	//	t.Skip()
	root := "Spec"
	halt, tree, ml, _, tr := seed(t, root)
	defer halt()

	mx, err := ml.FeedManifests(true, true, true, lists.NewFileList().ListDir(tree.CWD)...)
	assert.NoError(t, err)

	err = tr.Upload(mx)
	assert.NoError(t, err)

	// make spec
	nameMap := map[string]proto.ID{}
	for name, m := range mx {
		nameMap[name] = m.ID
	}

	spec1, err := proto.NewSpec(time.Now().UnixNano(), nameMap, []string{})
	assert.NoError(t, err)

	err = tr.UploadSpec(spec1)
	assert.NoError(t, err)

	spec2, err := tr.GetSpec(spec1.ID)
	assert.NoError(t, err)

	assert.Equal(t, spec1.ID, spec2.ID)
}
Ejemplo n.º 8
0
func TestEnum_ComputeInstance(t *testing.T) {
	// ensure that the enum validation for the anonymous object under the delegate property
	// is rendered.
	specDoc, err := spec.Load("../fixtures/codegen/todolist.enums.yml")
	if assert.NoError(t, err) {
		definitions := specDoc.Spec().Definitions
		k := "ComputeInstance"
		schema := definitions[k]
		genModel, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			buf := bytes.NewBuffer(nil)
			err := modelTemplate.Execute(buf, genModel)
			if assert.NoError(t, err) {
				ff, err := formatGoFile("object_thing.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(ff)
					fmt.Println(res)
					assertInCode(t, "Region string `json:\"region,omitempty\"`", res)
					assertInCode(t, "var computeInstanceRegionEnum []interface{}", res)
					assertInCode(t, "m.validateRegionEnum(\"region\", \"body\", m.Region)", res)
				}
			}
		}
	}
}
Ejemplo n.º 9
0
func TestEnum_NewPrototype(t *testing.T) {
	// ensure that the enum validation for the anonymous object under the delegate property
	// is rendered.
	specDoc, err := spec.Load("../fixtures/codegen/todolist.enums.yml")
	if assert.NoError(t, err) {
		definitions := specDoc.Spec().Definitions
		k := "NewPrototype"
		schema := definitions[k]
		genModel, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			buf := bytes.NewBuffer(nil)
			err := modelTemplate.Execute(buf, genModel)
			if assert.NoError(t, err) {
				ff, err := formatGoFile("object_thing.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(ff)
					assertInCode(t, "ActivatingUser NewPrototypeActivatingUser `json:\"activating_user,omitempty\"`", res)
					assertInCode(t, "Delegate NewPrototypeDelegate `json:\"delegate\"`", res)
					assertInCode(t, "Role string `json:\"role\"`", res)
					assertInCode(t, "var newPrototypeRoleEnum []interface{}", res)
					assertInCode(t, "var newPrototypeDelegateKindEnum []interface{}", res)
					assertInCode(t, "m.validateDelegate(formats)", res)
					assertInCode(t, "m.validateRole(formats)", res)
					assertInCode(t, "m.validateActivatingUser(formats)", res)
					assertInCode(t, "m.Delegate.Validate(formats)", res)
					assertInCode(t, "m.ActivatingUser.Validate(formats)", res)
				}
			}
		}
	}
}
Ejemplo n.º 10
0
func TestEnum_SliceAndAdditionalItemsThing(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.enums.yml")
	if assert.NoError(t, err) {
		definitions := specDoc.Spec().Definitions
		k := "SliceAndAdditionalItemsThing"
		schema := definitions[k]
		genModel, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			buf := bytes.NewBuffer(nil)
			err := modelTemplate.Execute(buf, genModel)
			if assert.NoError(t, err) {
				ff, err := formatGoFile("slice_and_additional_items_thing.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(ff)
					assertInCode(t, "var sliceAndAdditionalItemsThingEnum []interface{}", res)
					assertInCode(t, k+") validateSliceAndAdditionalItemsThingEnum(path, location string, value SliceAndAdditionalItemsThing)", res)
					//assertInCode(t, "m.validateSliceAndAdditionalItemsThingEnum(\"\", \"body\", m)", res)
					assertInCode(t, "var sliceAndAdditionalItemsThingP0Enum []interface{}", res)
					assertInCode(t, k+") validateP0Enum(path, location string, value string)", res)
					assertInCode(t, "m.validateP0Enum(\"0\", \"body\", m.P0)", res)
					assertInCode(t, "var sliceAndAdditionalItemsThingItemsEnum []interface{}", res)
					assertInCode(t, k+") validateSliceAndAdditionalItemsThingItemsEnum(path, location string, value float32)", res)
					assertInCode(t, "m.validateSliceAndAdditionalItemsThingItemsEnum(strconv.Itoa(i+1), \"body\", m.SliceAndAdditionalItemsThingItems[i])", res)
				}
			}
		}
	}
}
Ejemplo n.º 11
0
func TestEnum_MapThing(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.enums.yml")
	if assert.NoError(t, err) {
		definitions := specDoc.Spec().Definitions
		k := "MapThing"
		schema := definitions[k]
		genModel, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			buf := bytes.NewBuffer(nil)
			err := modelTemplate.Execute(buf, genModel)
			if assert.NoError(t, err) {
				ff, err := formatGoFile("map_thing.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(ff)
					assertInCode(t, "var mapThingEnum []interface{}", res)
					assertInCode(t, k+") validateMapThingEnum(path, location string, value map[string]string)", res)
					assertInCode(t, "m.validateMapThingEnum(\"\", \"body\", m)", res)
					assertInCode(t, "var mapThingValueEnum []interface{}", res)
					assertInCode(t, k+") validateMapThingValueEnum(path, location string, value string)", res)
					assertInCode(t, "m.validateMapThingValueEnum(k, \"body\", m[k])", res)
				}
			}
		}
	}
}
Ejemplo n.º 12
0
func addTarget(t *testing.T, repo *NotaryRepository, targetName, targetFile string) *Target {
	target, err := NewTarget(targetName, targetFile)
	assert.NoError(t, err, "error creating target")
	err = repo.AddTarget(target)
	assert.NoError(t, err, "error adding target")
	return target
}
Ejemplo n.º 13
0
// Test for expired key and see if RefreshLogin can restore the key if we have a bad key
func TestSessionExpiredKey(t *testing.T) {
	var (
		c *ICSPClient
		d *ICSPTest
	)
	if os.Getenv("ONEVIEW_TEST_ACCEPTANCE") == "true" {
		d, c = getTestDriverA()
		if c == nil {
			t.Fatalf("Failed to execute getTestDriver() ")
		}
		err := c.RefreshLogin()
		log.Debugf(" login key -> %s", c.APIKey)
		assert.NoError(t, err, "RefreshLogin threw error -> %s", err)
		// force key to timeout
		err = c.SetIdleTimeout(800)
		assert.NoError(t, err, "SetIdleTimeout threw error -> %s", err)

		// 1 millisecond and we should be timeout with the current key
		time.Sleep(1 * time.Millisecond)

		// verify we are timed out
		_, err = c.GetIdleTimeout()
		assert.Error(t, err, "should be 404 not found -> %s ", err)

		// verify that we can access something from icps with this client
		// This should not fail because it uses RefreshLogin to get a new login session and avoid timeout
		serialNumber := d.Tc.GetTestData(d.Env, "SerialNumber").(string)
		s, err := c.GetServerBySerialNumber(serialNumber)
		assert.NoError(t, err, "GetServerBySerialNumber threw error -> %s, server -> %+v", err, s)
	}

}
Ejemplo n.º 14
0
// Set idle timeout
func TestSetIdleTimeout(t *testing.T) {
	var (
		c *ICSPClient
		// d *ICSPTest
		testtime int64
	)
	if os.Getenv("ONEVIEW_TEST_ACCEPTANCE") == "true" {
		testtime = 25000
		_, c = getTestDriverA()
		if c == nil {
			t.Fatalf("Failed to execute getTestDriver() ")
		}
		err := c.RefreshLogin()
		log.Debugf(" login key -> %s", c.APIKey)
		assert.NoError(t, err, "RefreshLogin threw error -> %s", err)

		err = c.SetIdleTimeout(testtime)
		assert.NoError(t, err, "SetIdleTimeout threw error -> %s", err)

		timeout, err := c.GetIdleTimeout()
		assert.NoError(t, err, "GetIdleTimeout threw error -> %s", err)
		assert.Equal(t, testtime, timeout, "Should get timeout equal, %s", timeout)
		log.Debugf(" idle timeout -> %d", timeout)
	}

}
Ejemplo n.º 15
0
func doTestPrefixScan(t *testing.T, node Node) {
	for i := 1; i < 3; i++ {
		n := node.From(fmt.Sprintf("%d%02d", 2015, i))
		err := n.Save(&SimpleUser{ID: i, Name: "John"})
		assert.NoError(t, err)
	}

	for i := 1; i < 4; i++ {
		n := node.From(fmt.Sprintf("%d%02d", 2016, i))
		err := n.Save(&SimpleUser{ID: i, Name: "John"})
		assert.NoError(t, err)
	}

	assert.Len(t, node.PrefixScan("2015"), 2)
	assert.Len(t, node.PrefixScan("20"), 5)

	buckets2016 := node.PrefixScan("2016")
	assert.Len(t, buckets2016, 3)
	count, err := buckets2016[1].Count(&SimpleUser{})

	assert.NoError(t, err)
	assert.Equal(t, 1, count)

	assert.NoError(t, buckets2016[1].One("ID", 2, &SimpleUser{}))
}
Ejemplo n.º 16
0
func TestExecutorDriverError(t *testing.T) {
	setTestEnv(t)
	// Mock Slave process to respond to registration event.
	server := testutil.NewMockSlaveHttpServer(t, func(rsp http.ResponseWriter, req *http.Request) {
		reqPath, err := url.QueryUnescape(req.URL.String())
		assert.NoError(t, err)
		log.Infoln("RCVD request", reqPath)
		rsp.WriteHeader(http.StatusAccepted)
	})

	ch := make(chan bool)
	exec := newTestExecutor(t)
	exec.ch = ch
	exec.t = t

	driver := newIntegrationTestDriver(t, exec)
	server.Close() // will cause error
	// Run() cause async message processing to start
	// Therefore, error-handling will be done via Executor.Error callaback.
	stat, err := driver.Run()
	assert.NoError(t, err)
	assert.Equal(t, mesos.Status_DRIVER_STOPPED, stat)

	select {
	case <-ch:
	case <-time.After(time.Millisecond * 5):
		log.Errorf("Tired of waiting...")
	}
}
Ejemplo n.º 17
0
func Test_Controller_Stats(t *testing.T) {
	repo, controller, mockTCPConn := setupControllerTest(t, 3)
	defer cleanupControllerTest(repo)

	q, err := repo.GetQueue("test")
	assert.NoError(t, err)

	cg, err := q.ConsumerGroup("cg1")
	assert.NoError(t, err)
	cg.GetNext()

	cg, err = q.ConsumerGroup("cg2")
	assert.NoError(t, err)
	cg.GetNext()
	cg.GetNext()

	err = controller.Stats()
	statsResponse := "STAT uptime 0\r\n" +
		fmt.Sprintf("STAT time %d\r\n", time.Now().Unix()) +
		"STAT version " + repo.Stats.Version + "\r\n" +
		"STAT curr_connections 1\r\n" +
		"STAT total_connections 1\r\n" +
		"STAT cmd_get 0\r\n" +
		"STAT cmd_set 0\r\n" +
		fmt.Sprintf("STAT queue_test_items %d\r\n", 3) +
		"STAT queue_test_open_transactions 0\r\n" +
		fmt.Sprintf("STAT queue_test.cg1_items %d\r\n", 2) +
		"STAT queue_test.cg1_open_transactions 0\r\n" +
		fmt.Sprintf("STAT queue_test.cg2_items %d\r\n", 1) +
		"STAT queue_test.cg2_open_transactions 0\r\n" +
		"END\r\n"
	assert.Nil(t, err)
	assert.Equal(t, statsResponse, mockTCPConn.WriteBuffer.String())
}
Ejemplo n.º 18
0
// TestGenerateSSHKey verifies that SSH key generation does indeed
// generate keys even with keys already exist.
func TestGenerateSSHKey(t *testing.T) {
	assert := assert.New(t)

	privateKey := generateTempFilePath("private")
	publicKey := generateTempFilePath("public")

	// Make sure we have no test keys laying around
	os.Remove(privateKey)
	os.Remove(publicKey)

	// Pass case: Sunny day case
	err := generateSSHKey(privateKey, publicKey)
	assert.NoError(err, "generateSSHKey should not have retuend an error: %s", err)

	// Pass case: PrivateKey exists test case
	os.Remove(publicKey)
	err = generateSSHKey(privateKey, publicKey)
	assert.NoError(err, "generateSSHKey should not have retuend an error: %s", err)

	// Pass case: PublicKey exists test case
	os.Remove(privateKey)
	err = generateSSHKey(privateKey, publicKey)
	assert.NoError(err, "generateSSHKey should not have retuend an error: %s", err)

	// Make sure we have no test keys laying around
	os.Remove(privateKey)
	os.Remove(publicKey)

	// TODO: testing error cases where the file can not be removed?
}
Ejemplo n.º 19
0
func Test_Transport_Download_Many(t *testing.T) {
	//	t.Skip()
	root := "Download-many"

	halt, tree, ml, _, tr := seed(t, root)
	defer halt()

	assert.NoError(t, tree.PopulateN(10, 1000))

	mx, err := ml.FeedManifests(true, true, true, lists.NewFileList().ListDir(tree.CWD)...)
	assert.NoError(t, err)

	err = tr.Upload(mx)
	assert.NoError(t, err)

	// Kill some blobs
	tree.KillBLOB("file-two.bin")
	tree.KillBLOB("one/file-two.bin")
	tree.KillBLOB("one/file-three.bin")
	req := lists.BlobMap{
		"file-two.bin":       mx["file-two.bin"],
		"one/file-two.bin":   mx["one/file-two.bin"],
		"one/file-three.bin": mx["one/file-three.bin"],
	}
	for i := 0; i < 256; i++ {
		nm := fmt.Sprintf("big/file-big-%d.bin", i)
		tree.KillBLOB(nm)
		req[nm] = mx[nm]
	}

	err = tr.Download(req)
	assert.NoError(t, err)
}
Ejemplo n.º 20
0
func TestUnCompressed(t *testing.T) {
	assert := assert.New(t)
	// SELECT repeat("a", 50)
	before := `
09 00 00 00 03 53 45 4c 45 43 54 20 31                ....SELECT 1
`
	after := `
0d 00 00 00 00 00 00 09    00 00 00 03 53 45 4c 45    ............SELE
43 54 20 31                                           CT 1
`
	_, _ = before, after

	buf := bytes.NewBufferString("")
	buf.Write(DecodeDump(after))

	r := NewCompressedReader(buf)
	b, err := ioutil.ReadAll(r)
	assert.NoError(err)
	assert.EqualValues(DecodeDump(before), b)

	// write and read again
	w := NewCompressedWriter(buf)
	_, err = w.Write(DecodeDump(before))
	assert.NoError(err)
	b, err = ioutil.ReadAll(r)
	assert.NoError(err)
	assert.EqualValues(DecodeDump(before), b)
}
Ejemplo n.º 21
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)
}
Ejemplo n.º 22
0
// TestGetNodeAddresses verifies that proper results are returned
// when requesting node addresses.
func TestGetNodeAddresses(t *testing.T) {
	master, etcdserver, _, assert := setUp(t)
	defer etcdserver.Terminate(t)

	// Fail case (no addresses associated with nodes)
	nodes, _ := master.nodeRegistry.ListNodes(api.NewDefaultContext(), nil)
	addrs, err := master.getNodeAddresses()

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

	// Pass case with External type IP
	nodes, _ = master.nodeRegistry.ListNodes(api.NewDefaultContext(), nil)
	for index := range nodes.Items {
		nodes.Items[index].Status.Addresses = []api.NodeAddress{{Type: api.NodeExternalIP, Address: "127.0.0.1"}}
	}
	addrs, err = master.getNodeAddresses()
	assert.NoError(err, "getNodeAddresses 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, _ = master.nodeRegistry.ListNodes(api.NewDefaultContext(), nil)
	for index := range nodes.Items {
		nodes.Items[index].Status.Addresses = []api.NodeAddress{{Type: api.NodeLegacyHostIP, Address: "127.0.0.2"}}
	}
	addrs, err = master.getNodeAddresses()
	assert.NoError(err, "getNodeAddresses failback should not have returned an error.")
	assert.Equal([]string{"127.0.0.2", "127.0.0.2"}, addrs)
}
func (suite *OauthTestSuite) TestRefreshTokenGrantScopeCannotBeGreater() {
	// Insert a test refresh token
	err := suite.db.Create(&oauth.RefreshToken{
		Token:     "test_token",
		ExpiresAt: time.Now().UTC().Add(+10 * time.Second),
		Client:    suite.clients[0],
		User:      suite.users[0],
		Scope:     "read_write",
	}).Error
	assert.NoError(suite.T(), err, "Inserting test data failed")

	// Prepare a request
	r, err := http.NewRequest("POST", "http://1.2.3.4/v1/oauth/tokens", nil)
	assert.NoError(suite.T(), err, "Request setup should not get an error")
	r.SetBasicAuth("test_client_1", "test_secret")
	r.PostForm = url.Values{
		"grant_type":    {"refresh_token"},
		"refresh_token": {"test_token"},
		"scope":         {"read read_write"},
	}

	// Serve the request
	w := httptest.NewRecorder()
	suite.router.ServeHTTP(w, r)

	// Check the response
	testutil.TestResponseForError(
		suite.T(),
		w,
		oauth.ErrRequestedScopeCannotBeGreater.Error(),
		400,
	)
}
Ejemplo n.º 24
0
func TestParseValidateAndSignCSR(t *testing.T) {
	tempBaseDir, err := ioutil.TempDir("", "swarm-ca-test-")
	assert.NoError(t, err)
	defer os.RemoveAll(tempBaseDir)

	paths := ca.NewConfigPaths(tempBaseDir)

	rootCA, err := ca.CreateAndWriteRootCA("rootCN", paths.RootCA)
	assert.NoError(t, err)

	csr, _, err := ca.GenerateAndWriteNewKey(paths.Node)
	assert.NoError(t, err)

	signedCert, err := rootCA.ParseValidateAndSignCSR(csr, "CN", "OU", "ORG")
	assert.NoError(t, err)
	assert.NotNil(t, signedCert)

	parsedCert, err := helpers.ParseCertificatesPEM(signedCert)
	assert.NoError(t, err)
	assert.Equal(t, 2, len(parsedCert))
	assert.Equal(t, "CN", parsedCert[0].Subject.CommonName)
	assert.Equal(t, 1, len(parsedCert[0].Subject.OrganizationalUnit))
	assert.Equal(t, "OU", parsedCert[0].Subject.OrganizationalUnit[0])
	assert.Equal(t, 3, len(parsedCert[0].Subject.Names))
	assert.Equal(t, "ORG", parsedCert[0].Subject.Organization[0])
	assert.Equal(t, "rootCN", parsedCert[1].Subject.CommonName)
}
Ejemplo n.º 25
0
func TestTypeResolver_AnonymousStructs(t *testing.T) {

	_, resolver, err := basicTaskListResolver(t)
	if assert.NoError(t, err) {
		// anonymous structs should be accounted for
		parent := new(spec.Schema)
		parent.Typed("object", "")
		parent.Properties = make(map[string]spec.Schema)
		parent.Properties["name"] = *spec.StringProperty()
		parent.Properties["age"] = *spec.Int32Property()

		rt, err := resolver.ResolveSchema(parent, true)
		if assert.NoError(t, err) {
			assert.False(t, rt.IsNullable)
			assert.True(t, rt.IsAnonymous)
			assert.True(t, rt.IsComplexObject)
		}

		parent.Extensions = make(spec.Extensions)
		parent.Extensions["x-isnullable"] = true

		rt, err = resolver.ResolveSchema(parent, true)
		if assert.NoError(t, err) {
			assert.True(t, rt.IsNullable)
			assert.True(t, rt.IsAnonymous)
			assert.True(t, rt.IsComplexObject)
		}
	}
}
Ejemplo n.º 26
0
func TestGetRemoteSignedCertificate(t *testing.T) {
	tc := testutils.NewTestCA(t)
	defer tc.Stop()

	// Create a new CSR to be signed
	csr, _, err := ca.GenerateAndWriteNewKey(tc.Paths.Node)
	assert.NoError(t, err)

	certs, err := ca.GetRemoteSignedCertificate(context.Background(), csr, tc.ManagerToken, tc.RootCA.Pool, tc.Remotes, nil, nil)
	assert.NoError(t, err)
	assert.NotNil(t, certs)

	// Test the expiration for a manager certificate
	parsedCerts, err := helpers.ParseCertificatesPEM(certs)
	assert.NoError(t, err)
	assert.Len(t, parsedCerts, 2)
	assert.True(t, time.Now().Add(ca.DefaultNodeCertExpiration).AddDate(0, 0, -1).Before(parsedCerts[0].NotAfter))
	assert.True(t, time.Now().Add(ca.DefaultNodeCertExpiration).AddDate(0, 0, 1).After(parsedCerts[0].NotAfter))
	assert.Equal(t, parsedCerts[0].Subject.OrganizationalUnit[0], ca.ManagerRole)

	// Test the expiration for an agent certificate
	certs, err = ca.GetRemoteSignedCertificate(tc.Context, csr, tc.WorkerToken, tc.RootCA.Pool, tc.Remotes, nil, nil)
	assert.NoError(t, err)
	assert.NotNil(t, certs)
	parsedCerts, err = helpers.ParseCertificatesPEM(certs)
	assert.NoError(t, err)
	assert.Len(t, parsedCerts, 2)
	assert.True(t, time.Now().Add(ca.DefaultNodeCertExpiration).AddDate(0, 0, -1).Before(parsedCerts[0].NotAfter))
	assert.True(t, time.Now().Add(ca.DefaultNodeCertExpiration).AddDate(0, 0, 1).After(parsedCerts[0].NotAfter))
	assert.Equal(t, parsedCerts[0].Subject.OrganizationalUnit[0], ca.AgentRole)
}
Ejemplo n.º 27
0
func TestGetActiveSession(t *testing.T) {
	kv := makeConsulClient(t)

	consul := kv.(*Consul)

	key := "foo"
	value := []byte("bar")

	// Put the first key with the Ephemeral flag
	err := kv.Put(key, value, &store.WriteOptions{TTL: 2 * time.Second})
	assert.NoError(t, err)

	// Session should not be empty
	session, err := consul.getActiveSession(key)
	assert.NoError(t, err)
	assert.NotEqual(t, session, "")

	// Delete the key
	err = kv.Delete(key)
	assert.NoError(t, err)

	// Check the session again, it should return nothing
	session, err = consul.getActiveSession(key)
	assert.NoError(t, err)
	assert.Equal(t, session, "")
}
Ejemplo n.º 28
0
func TestGetRemoteSignedCertificateWithPending(t *testing.T) {
	tc := testutils.NewTestCA(t)
	defer tc.Stop()

	// Create a new CSR to be signed
	csr, _, err := ca.GenerateAndWriteNewKey(tc.Paths.Node)
	assert.NoError(t, err)

	updates, cancel := state.Watch(tc.MemoryStore.WatchQueue(), state.EventCreateNode{})
	defer cancel()

	completed := make(chan error)
	go func() {
		_, err := ca.GetRemoteSignedCertificate(context.Background(), csr, tc.WorkerToken, tc.RootCA.Pool, tc.Remotes, nil, nil)
		completed <- err
	}()

	event := <-updates
	node := event.(state.EventCreateNode).Node.Copy()

	// Directly update the status of the store
	err = tc.MemoryStore.Update(func(tx store.Tx) error {
		node.Certificate.Status.State = api.IssuanceStateIssued

		return store.UpdateNode(tx, node)
	})
	assert.NoError(t, err)

	// Make sure GetRemoteSignedCertificate didn't return an error
	assert.NoError(t, <-completed)
}
Ejemplo n.º 29
0
func testAtomicPutCreate(t *testing.T, kv store.Store) {
	// Use a key in a new directory to ensure Stores will create directories
	// that don't yet exist.
	key := "testAtomicPutCreate/create"
	value := []byte("putcreate")

	// AtomicPut the key, previous = nil indicates create.
	success, _, err := kv.AtomicPut(key, value, nil, nil)
	assert.NoError(t, err)
	assert.True(t, success)

	// Get should return the value and an incremented index
	pair, err := kv.Get(key)
	assert.NoError(t, err)
	if assert.NotNil(t, pair) {
		assert.NotNil(t, pair.Value)
	}
	assert.Equal(t, pair.Value, value)

	// Attempting to create again should fail.
	success, _, err = kv.AtomicPut(key, value, nil, nil)
	assert.Error(t, err)
	assert.False(t, success)

	// This CAS should succeed, since it has the value from Get()
	success, _, err = kv.AtomicPut(key, []byte("PUTCREATE"), pair, nil)
	assert.NoError(t, err)
	assert.True(t, success)
}
Ejemplo n.º 30
0
// Test SessionLogout
func TestSessionLogout(t *testing.T) {
	var (
		//d *OVTest
		c *ICSPClient
		//testSerial string
	)
	if os.Getenv("ONEVIEW_TEST_ACCEPTANCE") == "true" {
		_, c = getTestDriverA()
		if c == nil {
			t.Fatalf("Failed to execute getTestDriver() ")
		}
		//data, err := c.SessionLogin()
		// this is needed so we can "copy" the session id to the ov client
		err := c.RefreshLogin()
		//log.Debugf(" login key -> %s, session data -> %+v", c.APIKey, data)
		log.Debugf(" login key -> %s", c.APIKey)
		assert.NoError(t, err, "SessionLogin threw error -> %s", err)
		//assert.NotEmpty(t, data.ID, fmt.Sprintf("SessionLogin is empty! something went wrong, err -> %s, data -> %+v\n", err, data))
		//assert.Equal(t, "none", c.APIKey)
		err = c.SessionLogout()
		log.Debugf(" login key after logout -> %s", c.APIKey)
		assert.NoError(t, err, "SessionLogout threw error -> %s", err)
		// test if we can perform an op after logout
		//_, err = c.GetProfileBySN(testSerial)
		//assert.Error(t, err, "SessionLogin threw error -> %s", err)
	} else {
		/*_, c = getTestDriverU()
		data, err := c.SessionLogin()
		assert.Error(t,err, fmt.Sprintf("ALL ok, no error, caught as expected: %s,%+v\n",err, data))
		assert.Equal(t, "none", c.APIKey)
		*/
	}
}