func TestErrorIsRateLimitShouldSucceed(t *testing.T) {

	sampleRateLimit := compute.RateLimit{
		NextAvailable: testTime,
		Remaining:     120,
		Unit:          "MINUTE",
		Value:         120,
		Verb:          "POST",
	}

	sampleBytes, _ := json.Marshal(sampleRateLimit)
	samplejson := `{ "limit": ` + string(sampleBytes) + " }"

	val := map[string][]string{"Content-Type": []string{"application/json"}}
	reader := testUtil.NewTestReadCloser([]byte(samplejson))
	response := http.Response{
		Header:     val,
		StatusCode: 413,
		Body:       reader,
	}
	httpStatus := misc.NewHTTPStatus(&response, "message")
	isRateLimit, rateLimit := compute.ErrorIsRateLimit(httpStatus)
	testUtil.Equals(t, true, isRateLimit)
	testUtil.Equals(t, sampleRateLimit, rateLimit)
}
func TestDefaultServiceResolverURLNotFoundInServiceCatalogError(t *testing.T) {
	apiServer := testVersionList(t)
	defer apiServer.Close()
	url, err := defaultGetVersionURLFilterByVersion("t", nil, []service{}, "image", "region1", "1")
	testUtil.Equals(t, "", url)
	testUtil.Assert(t, err != nil, "Expected an error")
	testUtil.Equals(t, "ServiceCatalog does not contain serviceType 'image'", err.Error())
}
func TestDefaultServiceURLFoundInCatalogErrorsNotFoundInVersionList(t *testing.T) {
	apiServer := testVersionList(t)
	defer apiServer.Close()
	sc := []service{createService("image", "glance", endpoint{Region: "region1", PublicURL: apiServer.URL + "/publicurl", VersionList: apiServer.URL + "/versionlist"})}
	url, err := defaultGetVersionURLFilterByVersion("t", nil, sc, "image", "region1", "2")
	testUtil.Equals(t, "", url)
	testUtil.Assert(t, err != nil, "Expected an error")
	testUtil.Equals(t, "Found serviceType 'image' in the ServiceCatalog but cannot find an endpoint with the specified region 'region1' and version '2'", err.Error())
}
func TestGetServerSecurityGroups(t *testing.T) {
	apiServer := testUtil.CreateGetJSONTestRequestServerVerifyURL(t, tokn, sampleSecurityGroupsJSONResponse, "/os-security-groups/servers/aghagr")
	defer apiServer.Close()

	service := CreateComputeService(apiServer.URL)
	sgs, err := service.ServerSecurityGroups("aghagr")
	testUtil.IsNil(t, err)
	testUtil.Equals(t, len(sgs), 1)
	testUtil.Equals(t, sampleSecurityGroup, sgs[0])
}
func TestEndpoints(t *testing.T) {
	apiServer := testUtil.CreateGetJSONTestRequestServerVerifyURL(t, tokn, hpHelionImageVersionPayload, "")
	defer apiServer.Close()

	versions, err := Endpoints(apiServer.URL, tokn, nil)
	testUtil.IsNil(t, err)
	numVersions := len(versions)
	testUtil.Equals(t, 2, numVersions)

	testUtil.Equals(t, "v1.1", versions[0].ID)
	testUtil.Equals(t, "CURRENT", versions[0].Status)

	testUtil.Equals(t, "v1.0", versions[1].ID)
	testUtil.Equals(t, "SUPPORTED", versions[1].Status)
}
func TestServiceURLNetworkV3Returns(t *testing.T) {
	sc := []service{createService("network", "neutron", testEndpoints...)}

	url, err := getAppendVersionServiceURL("t", nil, sc, "network", "region2", "3")
	testUtil.IsNil(t, err)
	testUtil.Equals(t, "http://endpoint2/v3", url)
}
func TestServiceURLComputeV3Returns(t *testing.T) {
	sc := []service{createService("computev3", "nova", testEndpoints...)}

	url, err := getComputeServiceURL("t", nil, sc, "compute", "region1", "3")
	testUtil.IsNil(t, err)
	testUtil.Equals(t, "http://endpoint1", url)
}
func TestPrivateCloudImagesDetail(t *testing.T) {
	// Read private cloud response content from file
	imagesTestFilePath := "./testdata/private_cloud_images_detail.json"
	imagesTestFileContent, err := ioutil.ReadFile(imagesTestFilePath)
	if err != nil {
		t.Error(fmt.Errorf("Failed to read JSON file %s: '%s'", imagesTestFilePath, err.Error()))
	}

	// Decode the content
	sampleImgs := imagesDetailResponse{}
	err = json.Unmarshal(imagesTestFileContent, &sampleImgs)
	if err != nil {
		t.Error(fmt.Errorf("Failed to decode JSON file %s: '%s'", imagesTestFilePath, err.Error()))
	}

	// Test the SDK API imageService.ImagesDetail()
	anon := func(imageService *image.Service) {
		images, err := imageService.ImagesDetail()
		if err != nil {
			t.Error(err)
		}

		if len(images) != len(sampleImgs.Images) {
			t.Error(errors.New("Incorrect number of images found"))
		}

		// Verify returned images match original sample images
		testUtil.Equals(t, sampleImgs.Images, images)
	}

	testImageServiceAction(t, "images/detail?limit=21", string(imagesTestFileContent), anon)
}
func TestListObjects(t *testing.T) {
	var objList = `[
		{"name":"test obj 1", 
		"hash":"4281c348eaf83e70ddce0e07221c3d28",
		"bytes":14,
		"content_type":"application\/octet-stream",
		"last_modified":"2009-02-03T05:26:32.612278"},
		{"name":"test obj 2",
		"hash":"b039efe731ad111bc1b0ef221c3849d0",
		"bytes":64,
		"content_type":"application\/octet-stream",
		"last_modified":"2009-02-03T05:26:32.612278"}
		]`
	var apiServer = httptest.NewServer(http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {
			if r.Method == "GET" {
				w.Header().Set("Content-Type", "application/json; charset=utf-8")
				w.WriteHeader(200)
				w.Write([]byte(objList))
				return
			}
			t.Error(errors.New("Failed: r.Method == GET"))
		}))
	defer apiServer.Close()
	myList, err := objectstorage.ListObjects(
		0, "", "", "", "", apiServer.URL+containerPrefix, tokn)
	if err != nil {
		t.Error(err)
	}

	testUtil.Equals(t, objList, string(myList))
}
示例#10
0
func TestGetFlavorsDetail(t *testing.T) {
	mockResponseObject := FlavorsDetailContainer{
		FlavorsDetail: []FlavorDetail{sampleFlavorDetail, sampleFlavorDetail2}}
	apiServer := testUtil.CreateGetJSONTestRequestServerWithMockObject(t, tokn, mockResponseObject, "/flavors/detail?limit=21")
	defer apiServer.Close()

	service := CreateComputeService(apiServer.URL)
	flavorsDetail, err := service.FlavorsDetail()
	testUtil.IsNil(t, err)

	if len(flavorsDetail) != 2 {
		t.Error(errors.New("Error: Expected 2 flavors detail to be listed"))
	}
	testUtil.Equals(t, sampleFlavorDetail, flavorsDetail[0])
	testUtil.Equals(t, sampleFlavorDetail2, flavorsDetail[1])
}
func TestCompabilitySecurityGroupPayloads(t *testing.T) {
	// Read private cloud response content from file
	securityGroupsTestFilePath := "./testdata/securitygroup_test_sgs.json"
	securityGroupsTestFileContent, err := ioutil.ReadFile(securityGroupsTestFilePath)
	if err != nil {
		t.Error(fmt.Errorf("Failed to read JSON file %s: '%s'", securityGroupsTestFilePath, err.Error()))
	}

	// Decode the content
	sampleSGs := compute.SecurityGroupsContainer{}
	err = json.Unmarshal(securityGroupsTestFileContent, &sampleSGs)
	if err != nil {
		t.Error(fmt.Errorf("Failed to decode JSON file %s: '%s'", securityGroupsTestFilePath, err.Error()))
	}

	// Test the SDK API computeService.SecurityGroups()
	anon := func(computeService *compute.Service) {

		securityGroups, err := computeService.SecurityGroups()
		if err != nil {
			t.Error(err)
		}

		if len(securityGroups) != len(sampleSGs.SecurityGroups) {
			t.Error(errors.New("Incorrect number of securityGroups found"))
		}

		// Verify returned availability zones match original sample availability zones
		testUtil.Equals(t, sampleSGs.SecurityGroups, securityGroups)
	}

	testComputeServiceAction(t, "os-security-groups", string(securityGroupsTestFileContent), anon)
}
示例#12
0
func TestCreateServer(t *testing.T) {
	apiServer := testUtil.CreatePostJSONTestRequestServer(t, tokn, createServerJSONPayload, "servers",
		`{"server":{"name":"my_server","imageRef":"8c3cd338-1282-4fbb-bbaf-2256ff97c7b7","key_name":"my_key_name","flavorRef":"101","maxcount":1,"mincount":1,"user_data":"my_user_data","availability_zone":"az1","networks":[{"uuid":"1111d337-0282-4fbb-bbaf-2256ff97c7b7","port":"881"}],"security_groups":[{"name":"my_security_group_123"}]}}`)
	defer apiServer.Close()

	serverService := CreateComputeService(apiServer.URL)
	az := "az1"
	userData := "my_user_data"
	maxMinCount := int32(1)
	var serverCreationParameters = ServerCreationParameters{
		Name:             "my_server",
		ImageRef:         "8c3cd338-1282-4fbb-bbaf-2256ff97c7b7",
		KeyPairName:      "my_key_name",
		FlavorRef:        "101",
		MaxCount:         &maxMinCount,
		MinCount:         &maxMinCount,
		AvailabilityZone: &az,
		UserData:         &userData,
		Networks:         []ServerNetworkParameters{ServerNetworkParameters{UUID: "1111d337-0282-4fbb-bbaf-2256ff97c7b7", Port: "881"}},
		SecurityGroups:   []SecurityGroup{SecurityGroup{Name: "my_security_group_123"}}}

	result, err := serverService.CreateServer(serverCreationParameters)
	testUtil.IsNil(t, err)

	testUtil.Equals(t, createServerResponse, result)
}
func TestGetSelfLinkNotFoundNoErrorOccurs(t *testing.T) {
	v := Version{Status: "CURRENT",
		ID:    "ID",
		Links: []Link{Link{HRef: "http://doc", Rel: "decribedby"}}}
	foundLink := v.GetSelfLink()
	testUtil.Equals(t, foundLink.HRef, "")
}
func TestPrivateCloudAvailabilityZones(t *testing.T) {

	// Read private cloud response content from file
	availabilityZonesTestFilePath := "./testdata/availabilityzone_test_azs.json"
	availabilityZonesTestFileContent, err := ioutil.ReadFile(availabilityZonesTestFilePath)
	if err != nil {
		t.Error(fmt.Errorf("Failed to read JSON file %s: '%s'", availabilityZonesTestFilePath, err.Error()))
	}

	// Decode the content
	sampleAzs := compute.AvailabilityZonesContainer{}
	err = json.Unmarshal(availabilityZonesTestFileContent, &sampleAzs)
	if err != nil {
		t.Error(fmt.Errorf("Failed to decode JSON file %s: '%s'", availabilityZonesTestFilePath, err.Error()))
	}

	// Test the SDK API computeService.AvailabilityZones()
	anon := func(computeService *compute.Service) {

		availabilityZones, err := computeService.AvailabilityZones()
		if err != nil {
			t.Error(err)
		}

		if len(availabilityZones) != len(sampleAzs.AvailabilityZones) {
			t.Error(errors.New("Incorrect number of availabilityZones found"))
		}

		// Verify returned availability zones match original sample availability zones
		testUtil.Equals(t, sampleAzs.AvailabilityZones, availabilityZones)
	}

	testComputeServiceAction(t, "os-availability-zone", string(availabilityZonesTestFileContent), anon)
}
func TestFindEndpointVersionNoValueFoundNoErrorShouldOccur(t *testing.T) {
	apiServer := testUtil.CreateGetJSONTestRequestServerVerifyURL(t, tokn, hpHelionImageVersionPayload, "")
	defer apiServer.Close()

	url, err := FindEndpointVersion(apiServer.URL, tokn, nil, "v2.0")
	testUtil.IsNil(t, err)
	testUtil.Equals(t, "", url)
}
func TestFindEndpointVersionValid(t *testing.T) {
	apiServer := testUtil.CreateGetJSONTestRequestServerVerifyURL(t, tokn, hpHelionImageVersionPayload, "")
	defer apiServer.Close()

	url, err := FindEndpointVersion(apiServer.URL, tokn, nil, "v1.0")
	testUtil.IsNil(t, err)
	testUtil.Equals(t, "http://region-a.geo-1.images.hpcloudsvc.com/v1/", url)
}
func TestDefaultServiceURLFoundInCatalogFoundInVersionList(t *testing.T) {
	apiServer := testVersionList(t)
	defer apiServer.Close()
	sc := []service{createService("image", "glance", endpoint{Region: "region1", PublicURL: apiServer.URL + "/publicurl", VersionList: apiServer.URL + "/versionlist"})}
	url, err := defaultGetVersionURLFilterByVersion("t", nil, sc, "image", "region1", "1")
	testUtil.IsNil(t, err)
	testUtil.Equals(t, "http://region-b.geo-1.image.hpcloudsvc.com/v1/", url)
}
func TestGetVolumeType(t *testing.T) {
	apiServer := testUtil.CreateGetJSONTestRequestServerVerifyStatusAndURL(t, tokn, 200, sampleVolumeTypeJson, "/types/id")
	defer apiServer.Close()

	service := CreateVolumeService(apiServer.URL)
	volume, err := service.VolumeType("id")
	testUtil.IsNil(t, err)
	testUtil.Equals(t, volumeTypeSample, volume)
}
示例#19
0
func TestGetFlavors(t *testing.T) {

	mockResponseObject := FlavorsContainer{
		Flavors: []Flavor{sampleFlavor, sampleFlavor2}}

	apiServer := testUtil.CreateGetJSONTestRequestServerWithMockObject(t, tokn, mockResponseObject, "/flavors")
	defer apiServer.Close()

	service := CreateDatabaseService(apiServer.URL)
	flavors, err := service.Flavors()
	testUtil.IsNil(t, err)

	if len(flavors) != 2 {
		t.Error(errors.New("Error: Expected 2 flavors to be listed"))
	}
	testUtil.Equals(t, sampleFlavor, flavors[0])
	testUtil.Equals(t, sampleFlavor2, flavors[1])
}
func TestGetSecurityGroup(t *testing.T) {
	apiServer := testUtil.CreateGetJSONTestRequestServerVerifyURL(t, tokn, sampleSecurityGroupJSONResponse, "/os-security-groups/w9236264")
	defer apiServer.Close()

	service := CreateComputeService(apiServer.URL)
	sg, err := service.SecurityGroup("w9236264")
	testUtil.IsNil(t, err)
	testUtil.Equals(t, sampleSecurityGroup, sg)
}
func createVolumeTypeTest(t *testing.T, p blockstorage.CreateVolumeTypeParameters, expectedPayload string) {
	apiServer := testUtil.CreatePostJSONTestRequestServer(t, tokn, sampleVolumeTypeJson, "types", expectedPayload)
	defer apiServer.Close()

	service := CreateVolumeService(apiServer.URL)
	volume, err := service.CreateVolumeType(p)
	testUtil.IsNil(t, err)

	testUtil.Equals(t, volumeTypeSample, volume)
}
func TestGetVolumeTypes(t *testing.T) {
	apiServer := testUtil.CreateGetJSONTestRequestServerVerifyStatusAndURL(t, tokn, 200, sampleVolumeTypesJson, "/types")
	defer apiServer.Close()

	service := CreateVolumeService(apiServer.URL)
	volumes, err := service.VolumeTypes()
	testUtil.IsNil(t, err)
	testUtil.Assert(t, len(volumes) == 1, "Expected 1 volume")
	testUtil.Equals(t, volumeTypeSample, volumes[0])
}
示例#23
0
func TestServerDetailNoImage(t *testing.T) {
	apiServer := testUtil.CreateGetJSONTestRequestServerVerifyURL(t, tokn, serverDetailNoImagePayload, "/servers/my_server")
	defer apiServer.Close()

	service := CreateComputeService(apiServer.URL)

	result, err := service.ServerDetail("my_server")
	testUtil.IsNil(t, err)

	testUtil.Equals(t, serverDetailNoImage, result)
}
示例#24
0
func TestGetUsers(t *testing.T) {

	mockResponseObject := UsersContainer{
		Users: []User{sampleUser1, sampleUser2}}

	apiServer := testUtil.CreateGetJSONTestRequestServerWithMockObject(t, tokn, mockResponseObject, "/users")
	defer apiServer.Close()

	service := CreateDatabaseService(apiServer.URL)
	users, err := service.Users(instanceID)
	if err != nil {
		t.Error(err)
	}

	if len(users) != 2 {
		t.Error(errors.New("Error: Expected 2 users to be listed"))
	}
	testUtil.Equals(t, sampleUser1, users[0])
	testUtil.Equals(t, sampleUser2, users[1])
}
func testVersionList(t *testing.T) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {
			testUtil.Equals(t, "GET", r.Method)
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusOK)
			w.Write([]byte(sampleImageVersionList))

			return
		}))
}
func TestGetDatabases(t *testing.T) {

	mockResponseObject := DatabasesContainer{
		Databases: []Database{sampleDatabase1, sampleDatabase2}}

	apiServer := testUtil.CreateGetJSONTestRequestServerWithMockObject(t, tokn, mockResponseObject, "/databases")
	defer apiServer.Close()

	service := CreateDatabaseService(apiServer.URL)
	databases, err := service.Databases(instanceID)
	if err != nil {
		t.Error(err)
	}

	if len(databases) != 2 {
		t.Error(errors.New("Error: Expected 2 databases to be listed"))
	}
	testUtil.Equals(t, sampleDatabase1, databases[0])
	testUtil.Equals(t, sampleDatabase2, databases[1])
}
示例#27
0
func TestQueryServersDetail(t *testing.T) {
	apiServer := testUtil.CreateGetJSONTestRequestServerVerifyURL(t, tokn, serversDetailJSONPayload, "/servers/detail?limit=21&name=foo")
	defer apiServer.Close()

	computeService := CreateComputeService(apiServer.URL)
	queryParameters := ServerDetailQueryParameters{Name: "foo"}
	servers, err := computeService.QueryServersDetail(queryParameters)

	testUtil.IsNil(t, err)
	testUtil.Assert(t, len(servers) == 1, "Expected 1 server.")
	testUtil.Equals(t, serverDetail, servers[0])
}
示例#28
0
func TestGetServerMetaItem(t *testing.T) {
	sampleMetadata := map[string]string{"status": "OK"}

	mockResponseObject := serverMetaItemContainer{Meta: sampleMetadata}
	apiServer := testUtil.CreateGetJSONTestRequestServerWithMockObject(t, tokn, mockResponseObject, "servers/"+testServeID+"/metadata/status")
	defer apiServer.Close()

	service := CreateComputeService(apiServer.URL)
	foundItem, err := service.ServerMetadataItem(testServeID, "status")
	testUtil.IsNil(t, err)
	testUtil.Equals(t, "OK", foundItem)
}
示例#29
0
func TestSetServerMetadata(t *testing.T) {
	sampleMetadata := map[string]string{"item": "value"}
	apiServer := CreateTestRequestServer(t, "POST", tokn, "/servers/"+testServeID+"/metadata", `{"metadata":{"item":"value"}}`, serverMetadataContainer{Metadata: sampleMetadata})
	defer apiServer.Close()

	service := CreateComputeService(apiServer.URL)
	actualMetadata, err := service.SetServerMetadata(testServeID, sampleMetadata)
	if err != nil {
		t.Error(err)
	}
	testUtil.Equals(t, sampleMetadata, actualMetadata)
}
示例#30
0
func TestPostJsonWithValidResponse(t *testing.T) {
	var apiServer = testUtil.CreatePostJSONTestRequestServer(t, token, `{"id":"id1","name":"Chris"}`, "", `{"id":"id1","name":"name"}`)
	defer apiServer.Close()
	actual := TestStruct{}
	ti := TestStruct{ID: "id1", Name: "name"}

	err := util.PostJSON(apiServer.URL, token, *http.DefaultClient, ti, &actual)
	testUtil.IsNil(t, err)
	expected := TestStruct{ID: "id1", Name: "Chris"}

	testUtil.Equals(t, expected, actual)
}