github.com/kyma-project/kyma-environment-broker@v0.0.1/internal/process/provisioning/internal_eval_test.go (about)

     1  package provisioning
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"net/http"
     7  	"net/http/httptest"
     8  	"strconv"
     9  	"testing"
    10  	"time"
    11  
    12  	"github.com/kyma-project/kyma-environment-broker/internal/broker"
    13  
    14  	"github.com/gorilla/mux"
    15  
    16  	"github.com/kyma-project/kyma-environment-broker/internal/avs"
    17  
    18  	"github.com/kyma-project/kyma-environment-broker/internal/storage"
    19  	"github.com/sirupsen/logrus"
    20  	"github.com/stretchr/testify/assert"
    21  )
    22  
    23  type evaluationRepository map[int64]*avs.BasicEvaluationCreateResponse
    24  
    25  type mockAvsService struct {
    26  	server     *httptest.Server
    27  	evals      evaluationRepository
    28  	isInternal bool
    29  	t          *testing.T
    30  }
    31  
    32  const dummyStrAvsTest = "dummy"
    33  
    34  func TestInternalEvaluationStep_Run(t *testing.T) {
    35  	// given
    36  	log := logrus.New()
    37  	memoryStorage := storage.NewMemoryStorage()
    38  	provisioningOperation := fixOperationCreateRuntime(t, broker.AzurePlanID, "westeurope")
    39  
    40  	inputCreator := newInputCreator()
    41  	provisioningOperation.InputCreator = inputCreator
    42  
    43  	err := memoryStorage.Operations().InsertOperation(provisioningOperation)
    44  	assert.NoError(t, err)
    45  
    46  	mockOauthServer := newMockAvsOauthServer()
    47  	defer mockOauthServer.Close()
    48  	mockAvsSvc := newMockAvsService(t, true)
    49  	mockAvsSvc.startServer()
    50  	defer mockAvsSvc.server.Close()
    51  	avsConfig := avsConfig(mockOauthServer, mockAvsSvc.server)
    52  	avsClient, err := avs.NewClient(context.TODO(), avsConfig, logrus.New())
    53  	assert.NoError(t, err)
    54  	avsDel := avs.NewDelegator(avsClient, avsConfig, memoryStorage.Operations())
    55  	internalEvalAssistant := avs.NewInternalEvalAssistant(avsConfig)
    56  	ies := NewInternalEvaluationStep(avsDel, internalEvalAssistant)
    57  
    58  	// when
    59  	logger := log.WithFields(logrus.Fields{"step": "TEST"})
    60  	provisioningOperation, repeat, err := ies.Run(provisioningOperation, logger)
    61  
    62  	//then
    63  	assert.NoError(t, err)
    64  	assert.Equal(t, 0*time.Second, repeat)
    65  
    66  	inDB, err := memoryStorage.Operations().GetOperationByID(provisioningOperation.ID)
    67  	assert.NoError(t, err)
    68  	assert.Contains(t, mockAvsSvc.evals, inDB.Avs.AvsEvaluationInternalId)
    69  }
    70  
    71  func TestInternalEvaluationStep_WhenOperationIsRepeatedWithIdPresent(t *testing.T) {
    72  	// given
    73  	log := logrus.New()
    74  	memoryStorage := storage.NewMemoryStorage()
    75  	provisioningOperation := fixOperationCreateRuntime(t, broker.AzurePlanID, "westeurope")
    76  	_, id := generateId()
    77  	provisioningOperation.Avs.AvsEvaluationInternalId = id
    78  
    79  	inputCreator := newInputCreator()
    80  	provisioningOperation.InputCreator = inputCreator
    81  
    82  	err := memoryStorage.Operations().InsertOperation(provisioningOperation)
    83  	assert.NoError(t, err)
    84  
    85  	mockOauthServer := newMockAvsOauthServer()
    86  	defer mockOauthServer.Close()
    87  	mockAvsServer := newMockAvsService(t, true)
    88  	mockAvsServer.startServer()
    89  	defer mockAvsServer.server.Close()
    90  	avsConfig := avsConfig(mockOauthServer, mockAvsServer.server)
    91  	avsClient, err := avs.NewClient(context.TODO(), avsConfig, logrus.New())
    92  	assert.NoError(t, err)
    93  	avsDel := avs.NewDelegator(avsClient, avsConfig, memoryStorage.Operations())
    94  	internalEvalAssistant := avs.NewInternalEvalAssistant(avsConfig)
    95  	ies := NewInternalEvaluationStep(avsDel, internalEvalAssistant)
    96  
    97  	// when
    98  	logger := log.WithFields(logrus.Fields{"step": "TEST"})
    99  	provisioningOperation, repeat, err := ies.Run(provisioningOperation, logger)
   100  
   101  	//then
   102  	assert.NoError(t, err)
   103  	assert.Equal(t, 0*time.Second, repeat)
   104  
   105  	inDB, err := memoryStorage.Operations().GetOperationByID(provisioningOperation.ID)
   106  	assert.NoError(t, err)
   107  	assert.Equal(t, inDB.Avs.AvsEvaluationInternalId, id)
   108  }
   109  
   110  func newMockAvsOauthServer() *httptest.Server {
   111  	return httptest.NewServer(
   112  		http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
   113  			writer.Header().Set("Content-Type", "application/json")
   114  			_, _ = writer.Write([]byte(`{"access_token": "90d64460d14870c08c81352a05dedd3465940a7c", "scope": "user", "token_type": "bearer", "expires_in": 86400}`))
   115  		}))
   116  }
   117  
   118  func newMockAvsService(t *testing.T, isInternal bool) *mockAvsService {
   119  	return &mockAvsService{
   120  		evals:      make(evaluationRepository, 0),
   121  		isInternal: isInternal,
   122  		t:          t,
   123  	}
   124  }
   125  
   126  func (svc *mockAvsService) startServer() {
   127  	r := mux.NewRouter()
   128  	r.HandleFunc("/", svc.handleCreateEvaluation).Methods(http.MethodPost)
   129  	r.HandleFunc("/{id}/tag", svc.handleAddTag).Methods(http.MethodPost)
   130  	svc.server = httptest.NewServer(r)
   131  }
   132  
   133  func (svc *mockAvsService) handleCreateEvaluation(w http.ResponseWriter, r *http.Request) {
   134  	assert.Equal(svc.t, r.Header.Get("Content-Type"), "application/json")
   135  	dec := json.NewDecoder(r.Body)
   136  	var requestObj avs.BasicEvaluationCreateRequest
   137  	err := dec.Decode(&requestObj)
   138  	assert.NoError(svc.t, err)
   139  
   140  	if svc.isInternal {
   141  		assert.Empty(svc.t, requestObj.URL)
   142  	} else {
   143  		assert.NotEmpty(svc.t, requestObj.URL)
   144  	}
   145  
   146  	evalCreateResponse := createResponseObj(requestObj, svc.t)
   147  	svc.evals[evalCreateResponse.Id] = evalCreateResponse
   148  
   149  	w.Header().Set("Content-Type", "application/json")
   150  	w.WriteHeader(http.StatusOK)
   151  	if err := json.NewEncoder(w).Encode(evalCreateResponse); err != nil {
   152  		w.WriteHeader(http.StatusInternalServerError)
   153  	}
   154  }
   155  
   156  func (svc *mockAvsService) handleAddTag(w http.ResponseWriter, r *http.Request) {
   157  	dec := json.NewDecoder(r.Body)
   158  	var requestObj *avs.Tag
   159  	err := dec.Decode(&requestObj)
   160  	assert.NoError(svc.t, err)
   161  
   162  	vars := mux.Vars(r)
   163  	evalId, err := strconv.ParseInt(vars["id"], 10, 64)
   164  	if err != nil {
   165  		w.WriteHeader(http.StatusBadRequest)
   166  	}
   167  	_, exists := svc.evals[evalId]
   168  	if !exists {
   169  		w.WriteHeader(http.StatusNotFound)
   170  	}
   171  	svc.evals[evalId].Tags = append(svc.evals[evalId].Tags, requestObj)
   172  
   173  	w.Header().Set("Content-Type", "application/json")
   174  	w.WriteHeader(http.StatusOK)
   175  	if err := json.NewEncoder(w).Encode(svc.evals[evalId]); err != nil {
   176  		w.WriteHeader(http.StatusInternalServerError)
   177  	}
   178  }
   179  
   180  func avsConfig(mockOauthServer *httptest.Server, mockAvsServer *httptest.Server) avs.Config {
   181  	return avs.Config{
   182  		OauthTokenEndpoint:     mockOauthServer.URL,
   183  		OauthUsername:          dummyStrAvsTest,
   184  		OauthPassword:          dummyStrAvsTest,
   185  		OauthClientId:          dummyStrAvsTest,
   186  		ApiEndpoint:            mockAvsServer.URL,
   187  		DefinitionType:         avs.DefinitionType,
   188  		InternalTesterAccessId: 1234,
   189  		InternalTesterService:  "",
   190  		ExternalTesterAccessId: 5678,
   191  		ExternalTesterService:  dummyStrAvsTest,
   192  
   193  		GroupId:          5555,
   194  		ParentId:         9101112,
   195  		RegionTagClassId: 111113,
   196  	}
   197  }
   198  
   199  func createResponseObj(requestObj avs.BasicEvaluationCreateRequest, t *testing.T) *avs.BasicEvaluationCreateResponse {
   200  	parseInt, err := strconv.ParseInt(requestObj.Threshold, 10, 64)
   201  	assert.NoError(t, err)
   202  
   203  	timeUnixEpoch, id := generateId()
   204  
   205  	evalCreateResponse := &avs.BasicEvaluationCreateResponse{
   206  		DefinitionType:             requestObj.DefinitionType,
   207  		Name:                       requestObj.Name,
   208  		Description:                requestObj.Description,
   209  		Service:                    requestObj.Service,
   210  		URL:                        requestObj.URL,
   211  		CheckType:                  requestObj.CheckType,
   212  		Interval:                   requestObj.Interval,
   213  		TesterAccessId:             requestObj.TesterAccessId,
   214  		Timeout:                    requestObj.Timeout,
   215  		ReadOnly:                   requestObj.ReadOnly,
   216  		ContentCheck:               requestObj.ContentCheck,
   217  		ContentCheckType:           requestObj.ContentCheck,
   218  		Threshold:                  parseInt,
   219  		GroupId:                    requestObj.GroupId,
   220  		Visibility:                 requestObj.Visibility,
   221  		DateCreated:                timeUnixEpoch,
   222  		DateChanged:                timeUnixEpoch,
   223  		Owner:                      "abc@xyz.corp",
   224  		Status:                     "ACTIVE",
   225  		Alerts:                     nil,
   226  		Tags:                       requestObj.Tags,
   227  		Id:                         id,
   228  		LegacyCheckId:              id,
   229  		InternalInterval:           60,
   230  		AuthType:                   "AUTH_NONE",
   231  		IndividualOutageEventsOnly: false,
   232  		IdOnTester:                 "",
   233  	}
   234  	return evalCreateResponse
   235  }
   236  
   237  func generateId() (int64, int64) {
   238  	timeUnixEpoch := time.Now().Unix()
   239  	id := time.Now().Unix()
   240  	return timeUnixEpoch, id
   241  }