<commit_before>//go:build !providerless
// +build !providerless

/*
Copyright 2020 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package azure

import (
	"fmt"
	"net/http"
	"strings"
	"testing"

	"k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/mockstorageaccountclient"
	"k8s.io/legacy-cloud-providers/azure/retry"

	"github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage"
	azstorage "github.com/Azure/azure-sdk-for-go/storage"
	autorestazure "github.com/Azure/go-autorest/autorest/azure"
	"github.com/Azure/go-autorest/autorest/to"
	"github.com/golang/mock/gomock"
	"github.com/stretchr/testify/assert"
)

var retryError500 = retry.Error{HTTPStatusCode: http.StatusInternalServerError}

func GetTestBlobDiskController(t *testing.T) BlobDiskController {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	az := GetTestCloud(ctrl)
	az.Environment = autorestazure.PublicCloud
	common := &controllerCommon{cloud: az, resourceGroup: "rg", location: "westus"}

	return BlobDiskController{
		common:   common,
		accounts: make(map[string]*storageAccountState),
	}
}

func TestInitStorageAccounts(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	b := GetTestBlobDiskController(t)
	b.accounts = nil

	mockSAClient := mockstorageaccountclient.NewMockInterface(ctrl)
	mockSAClient.EXPECT().ListByResourceGroup(gomock.Any(), b.common.resourceGroup).Return([]storage.Account{}, &retryError500)
	b.common.cloud.StorageAccountClient = mockSAClient

	b.initStorageAccounts()
	assert.Empty(t, b.accounts)

	mockSAClient.EXPECT().ListByResourceGroup(gomock.Any(), b.common.resourceGroup).Return([]storage.Account{
		{
			Name: to.StringPtr("ds-0"),
			Sku:  &storage.Sku{Name: "sku"},
		},
	}, nil)
	b.common.cloud.StorageAccountClient = mockSAClient

	b.initStorageAccounts()
	assert.Equal(t, 1, len(b.accounts))
}

func TestCreateVolume(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	b := GetTestBlobDiskController(t)

	mockSAClient := mockstorageaccountclient.NewMockInterface(ctrl)
	mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, "testsa").Return(storage.AccountListKeysResult{}, &retryError500)
	b.common.cloud.StorageAccountClient = mockSAClient

	diskName, diskURI, requestGB, err := b.CreateVolume("testBlob", "testsa", "type", b.common.location, 10)
	expectedErr := fmt.Errorf("could not get storage key for storage account testsa: could not get storage key for "+
		"storage account testsa: Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: %w", error(nil))
	assert.Equal(t, expectedErr, err)
	assert.Empty(t, diskName)
	assert.Empty(t, diskURI)
	assert.Zero(t, requestGB)

	mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, "testsa").Return(storage.AccountListKeysResult{
		Keys: &[]storage.AccountKey{
			{
				KeyName: to.StringPtr("key1"),
				Value:   to.StringPtr("dmFsdWUK"),
			},
		},
	}, nil)
	diskName, diskURI, requestGB, err = b.CreateVolume("testBlob", "testsa", "type", b.common.location, 10)
	expectedErrStr := "failed to put page blob testBlob.vhd in container vhds: storage: service returned error: StatusCode=403, ErrorCode=AccountIsDisabled, ErrorMessage=The specified account is disabled."
	assert.Error(t, err)
	assert.True(t, strings.Contains(err.Error(), expectedErrStr))
	assert.Empty(t, diskName)
	assert.Empty(t, diskURI)
	assert.Zero(t, requestGB)
}

func TestDeleteVolume(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	b := GetTestBlobDiskController(t)
	b.common.cloud.BlobDiskController = &b

	mockSAClient := mockstorageaccountclient.NewMockInterface(ctrl)
	mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, "foo").Return(storage.AccountListKeysResult{}, &retryError500).Times(2)
	b.common.cloud.StorageAccountClient = mockSAClient

	fakeDiskURL := "fake"
	diskURL := "https://foo.blob./vhds/bar.vhd"
	err := b.DeleteVolume(diskURL)
	expectedErr := fmt.Errorf("no key for storage account foo, err Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: %w", error(nil))
	assert.Equal(t, expectedErr, err)

	err = b.DeleteVolume(diskURL)
	assert.Equal(t, expectedErr, err)

	mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, "foo").Return(storage.AccountListKeysResult{<commit_msg>Switch to assert.ErrorEquals from assert.Equal to check error equality<commit_after>//go:build !providerless
// +build !providerless

/*
Copyright 2020 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package azure

import (
	"fmt"
	"net/http"
	"strings"
	"testing"

	"k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/mockstorageaccountclient"
	"k8s.io/legacy-cloud-providers/azure/retry"

	"github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage"
	azstorage "github.com/Azure/azure-sdk-for-go/storage"
	autorestazure "github.com/Azure/go-autorest/autorest/azure"
	"github.com/Azure/go-autorest/autorest/to"
	"github.com/golang/mock/gomock"
	"github.com/stretchr/testify/assert"
)

var retryError500 = retry.Error{HTTPStatusCode: http.StatusInternalServerError}

func GetTestBlobDiskController(t *testing.T) BlobDiskController {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	az := GetTestCloud(ctrl)
	az.Environment = autorestazure.PublicCloud
	common := &controllerCommon{cloud: az, resourceGroup: "rg", location: "westus"}

	return BlobDiskController{
		common:   common,
		accounts: make(map[string]*storageAccountState),
	}
}

func TestInitStorageAccounts(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	b := GetTestBlobDiskController(t)
	b.accounts = nil

	mockSAClient := mockstorageaccountclient.NewMockInterface(ctrl)
	mockSAClient.EXPECT().ListByResourceGroup(gomock.Any(), b.common.resourceGroup).Return([]storage.Account{}, &retryError500)
	b.common.cloud.StorageAccountClient = mockSAClient

	b.initStorageAccounts()
	assert.Empty(t, b.accounts)

	mockSAClient.EXPECT().ListByResourceGroup(gomock.Any(), b.common.resourceGroup).Return([]storage.Account{
		{
			Name: to.StringPtr("ds-0"),
			Sku:  &storage.Sku{Name: "sku"},
		},
	}, nil)
	b.common.cloud.StorageAccountClient = mockSAClient

	b.initStorageAccounts()
	assert.Equal(t, 1, len(b.accounts))
}

func TestCreateVolume(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	b := GetTestBlobDiskController(t)

	mockSAClient := mockstorageaccountclient.NewMockInterface(ctrl)
	mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, "testsa").Return(storage.AccountListKeysResult{}, &retryError500)
	b.common.cloud.StorageAccountClient = mockSAClient

	diskName, diskURI, requestGB, err := b.CreateVolume("testBlob", "testsa", "type", b.common.location, 10)
	expectedErr := fmt.Errorf("could not get storage key for storage account testsa: could not get storage key for "+
		"storage account testsa: Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: %w", error(nil))
	assert.EqualError(t, err, expectedErr.Error())
	assert.Empty(t, diskName)
	assert.Empty(t, diskURI)
	assert.Zero(t, requestGB)

	mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, "testsa").Return(storage.AccountListKeysResult{
		Keys: &[]storage.AccountKey{
			{
				KeyName: to.StringPtr("key1"),
				Value:   to.StringPtr("dmFsdWUK"),
			},
		},
	}, nil)
	diskName, diskURI, requestGB, err = b.CreateVolume("testBlob", "testsa", "type", b.common.location, 10)
	expectedErrStr := "failed to put page blob testBlob.vhd in container vhds: storage: service returned error: StatusCode=403, ErrorCode=AccountIsDisabled, ErrorMessage=The specified account is disabled."
	assert.Error(t, err)
	assert.True(t, strings.Contains(err.Error(), expectedErrStr))
	assert.Empty(t, diskName)
	assert.Empty(t, diskURI)
	assert.Zero(t, requestGB)
}

func TestDeleteVolume(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	b := GetTestBlobDiskController(t)
	b.common.cloud.BlobDiskController = &b

	mockSAClient := mockstorageaccountclient.NewMockInterface(ctrl)
	mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, "foo").Return(storage.AccountListKeysResult{}, &retryError500).Times(2)
	b.common.cloud.StorageAccountClient = mockSAClient

	fakeDiskURL := "fake"
	diskURL := "https://foo.blob./vhds/bar.vhd"
	err := b.DeleteVolume(diskURL)
	expectedErr := fmt.Errorf("no key for storage account foo, err Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: %w", error(nil))
	assert.EqualError(t, err, expectedErr.Error())

	err = b.DeleteVolume(diskURL)
	assert.EqualError(t, err, expectedErr.Error())

	mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, "foo").Return(storage.AccountListKeysResult{
{'fraction_non_alphanumeric': 0.13138461538461538, 'fraction_numerical': 0.010051282051282051, 'mean_word_length': 5.734116022099448, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2218078', 'n_tokens_mistral': 3319, 'n_tokens_neox': 3236, 'n_words': 677}