Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package execution
- import (
- "bytes"
- "context"
- "encoding/base64"
- "encoding/json"
- "fmt"
- apiModels "github.com/ContinuumLLC/platform-api-model/clients/model/Golang/resourceModel/tasking"
- "github.com/ContinuumLLC/platform-scripting-service/src/app-loader"
- "github.com/ContinuumLLC/platform-scripting-service/src/middlewares/transaction-id"
- "github.com/ContinuumLLC/platform-scripting-service/src/model-mocks"
- "github.com/ContinuumLLC/platform-scripting-service/src/models"
- "github.com/ContinuumLLC/platform-scripting-service/src/services/common"
- "github.com/gocql/gocql"
- "github.com/gorilla/mux"
- "github.com/pkg/errors"
- "net/http"
- "net/http/httptest"
- "reflect"
- "strings"
- "testing"
- "time"
- )
- const (
- baseURL = "/ss/v1/partners"
- postExecutionPayloadURL = baseURL + "/{partnerID}/execute"
- )
- var (
- ctx context.Context
- service Service
- scriptRepo models.ScriptingPersistence
- executionsRepo models.ExecutionPersistence
- testTransactionID, _ = gocql.ParseUUID("00000000-0000-0000-0000-000000000022")
- )
- func init() {
- appLoader.LoadApplicationServices(true)
- }
- func setUp(fillScriptMock, fillExectuionsMock bool) {
- scriptRepo = modelMocks.NewScriptRepoMock(fillScriptMock)
- executionMock := modelMocks.NewExectuionRepoMock(fillExectuionsMock)
- service = NewService(scriptRepo, executionMock)
- ctx = context.WithValue(ctx, transactionId.TransactionIDKey, testTransactionID)
- }
- func tireDown() {
- }
- func TestRunExecutionWithEmptyPayload(t *testing.T) {
- setUp(true, false)
- defer tireDown()
- sendRequest(t, string(""), "POST", postExecutionPayloadURL, 500)
- }
- func TestInsertParametersIntoScriptBody(t *testing.T) {
- tests := []struct {
- parameters string
- expectedResult []string
- }{
- {
- `{ "force" : false, "userName": "Name1", "int":1, "float":1.1,"array":[ "Ford", "BMW", "Fiat" ], "floatArray":[1.1,2.2,3.3]}`,
- []string{"$force=$false", `$userName="Name1"`, "$int=1", "$float=1.1", "$array=\"Ford\",\"BMW\",\"Fiat\"", "$floatArray=1.1,2.2,3.3"},
- },
- }
- for _, test := range tests {
- scriptBody, err := addParametersToTheBeginnigOfScriptBody(test.parameters, "someScript")
- if err != nil {
- t.Fatalf("Incorrect result. error %v", err)
- }
- for _, expected := range test.expectedResult {
- if !strings.Contains(scriptBody, expected) {
- t.Fatalf("Incorrect result. expected %v but obtained %v", expected, scriptBody)
- }
- }
- }
- }
- func TestValidateJob(t *testing.T) {
- uuid := "12940ab9-f577-4c73-ac26-2a7ed56e6615"
- var payloads []apiModels.ExecutionPayload
- payloads = append(payloads, apiModels.ExecutionPayload{
- Parameters: "",
- ManagedEndpointID: uuid,
- OriginID: uuid,
- ExecutionID: uuid,
- HookURL: "http://someURL",
- }, apiModels.ExecutionPayload{
- Parameters: `{"name":"UserName1", "password":"paswd123"}`,
- ManagedEndpointID: uuid,
- OriginID: uuid,
- ExecutionID: uuid,
- HookURL: "http://someURL",
- })
- err := validateJob(payloads)
- if err != nil {
- t.Fatalf("Error:%v", err)
- }
- }
- func TestValidateJobException(t *testing.T) {
- uuid := "12940ab9-f577-4c73-ac26-2a7ed56e6615"
- var payloads []apiModels.ExecutionPayload
- payloads = append(payloads, apiModels.ExecutionPayload{
- Parameters: "",
- ExecutionID: "",
- OriginID: uuid,
- ManagedEndpointID: uuid,
- HookURL: "http://someURL",
- })
- err := validateJob(payloads)
- if err == nil {
- t.Fatal("Error should not be nil when ExecutionPayload.ExecutionID is empty")
- }
- }
- func TestCreateExecutionMessage(t *testing.T) {
- var payload apiModels.ExecutionPayload
- var script apiModels.Script
- var executionMessage models.ExecutionMessage
- var err error
- uuid := "12940ab9-f577-4c73-ac26-2a7ed56e6615"
- payload = apiModels.ExecutionPayload{
- Parameters: `{"name":"UserName1", "password":"paswd123"}`,
- ManagedEndpointID: uuid,
- OriginID: uuid,
- ExecutionID: uuid,
- HookURL: "http://someURL",
- }
- timeNow := time.Now()
- script = apiModels.Script{
- CreatedAt: timeNow,
- ID: uuid,
- Engine: "engine",
- Content: "Z3B1cGRhdGUgL2ZvcmNl",
- Name: "name",
- Description: "description",
- Categories: []string{"patch", "script"},
- PartnerID: "507231",
- }
- executionMessage, err = createExecutionMessage(payload, script)
- if err != nil {
- t.Errorf("Error:%v", err)
- }
- schedule := "SCHEDULE"
- if executionMessage.Type != schedule {
- t.Errorf("Incorrect type %v expected %v", executionMessage.Type, schedule)
- }
- version := "1.0"
- if executionMessage.Version != version {
- t.Errorf("Incorrect Version %v expected %v", executionMessage.Version, version)
- }
- path := "/scripting/scripting/command"
- if executionMessage.Path != path {
- t.Errorf("Incorrect path %v expected %v", executionMessage.Path, path)
- }
- var m models.Message
- err = json.Unmarshal([]byte(executionMessage.Message), &m)
- if err != nil {
- t.Errorf("Error %v while unmarshal message %v", err, executionMessage.Message)
- }
- task := "/schedule/"
- if m.Task != task {
- t.Errorf("Incorrect task %v expected %v", m.Task, task)
- }
- if m.ExecuteNow != "true" {
- t.Errorf("Incorrect executeNow %v expected %v", m.ExecuteNow, true)
- }
- if m.Schedule != "" {
- t.Errorf("Incorrect schedule %v expected %v", m.Schedule, "")
- }
- taskInputBin, err := base64.StdEncoding.DecodeString(m.TaskInput)
- if err != nil {
- t.Fatalf("Can't decode task input from Base64: %v", err)
- }
- var taskInput models.TaskInput
- err = json.Unmarshal(taskInputBin, &taskInput)
- if err != nil {
- t.Fatalf("Can't decode task input from JSON: %v", err)
- }
- if taskInput.ExecutionID.String() != uuid {
- t.Errorf("Incorrect ExecutionID %v expected %v", taskInput.ExecutionID, uuid)
- }
- if !strings.Contains(taskInput.Script.Body, "$password=\"paswd123\"") || !strings.Contains(taskInput.Script.Body, "$name=\"UserName1\"") {
- t.Errorf("Incorrect taskInput.Script: absence of some of parameters")
- }
- if !strings.Contains(taskInput.Script.Body, "gpupdate /force") {
- t.Errorf("Incorrect taskInput.Script: absence of script body")
- }
- if taskInput.Script.Executor != "engine" {
- t.Errorf("Incorrect taskInput.Script.Executor %v expected engine", taskInput.Script.Executor)
- }
- }
- func TestRunExecutionEmptyPayload(t *testing.T) {
- setUp(true, false)
- defer tireDown()
- sendRequest(t,
- string(`[]`),
- "POST", "/ss/v1/partners/123456789/execute", 400)
- }
- func TestAddValueToBuffer(t *testing.T) {
- tests := []struct {
- values []interface{}
- expectedResult string
- }{
- {
- values: []interface{}{"param1", 22, true},
- expectedResult: "\"param1\"22$true",
- },
- {
- values: []interface{}{"username@gmail.com", "password#@$true", 3.14, "zd", 2.718, "c"},
- expectedResult: `"username@gmail.com""password#@$true"3.14"zd"2.718"c"`,
- },
- }
- for _, test := range tests {
- buffer := &bytes.Buffer{}
- for _, value := range test.values {
- addValueToBuffer(buffer, value)
- }
- if buffer.String() != test.expectedResult {
- t.Fatalf("Expected %s, but got %s", test.expectedResult, buffer.String())
- }
- }
- }
- func TestExtractPayload(t *testing.T) {
- payload := apiModels.ExecutionPayload{
- ExecutionID: "ExecutionID",
- ManagedEndpointID: "ManagedEndpointID",
- HookURL: "http://loclahost",
- OriginID: "OriginID",
- Parameters: "paramaters-bla-bla-bla",
- }
- payloadBin, _ := json.Marshal([]apiModels.ExecutionPayload{payload})
- tests := []struct {
- requestBody string
- requestMethod string
- expectedResult []apiModels.ExecutionPayload
- err error
- }{
- {
- requestMethod: "POST",
- requestBody: "aaa",
- err: errors.New("Can't unmarshal input data: aaa (err: invalid character 'a' looking for beginning of value)"),
- },
- {
- requestMethod: "POST",
- requestBody: string(payloadBin),
- expectedResult: []apiModels.ExecutionPayload{payload},
- },
- }
- for _, test := range tests {
- req, err := http.NewRequest(test.requestMethod, "http://localhost", bytes.NewReader([]byte(test.requestBody)))
- if err != nil {
- t.Fatalf("Can't create request, err: %v", err)
- }
- actualPayload, err := extractPayload(req)
- if err != nil && test.err != nil && (err.Error() != test.err.Error()) {
- t.Fatalf("Expected error %v, but got %v", test.err, err)
- }
- if !reflect.DeepEqual(actualPayload, test.expectedResult) {
- t.Fatalf("Expected result %v, but got %v", test.expectedResult, actualPayload)
- }
- }
- }
- // =================Internal functions===========================
- func startTestServer() *mux.Router {
- router := mux.NewRouter()
- router.HandleFunc(postExecutionPayloadURL, http.HandlerFunc(service.RunExecution)).Methods("POST")
- return router
- }
- func checkStatus(t *testing.T, status int, rec *httptest.ResponseRecorder) {
- if rec.Code != status {
- t.Fatalf("expected the status %d but got %d\n", status, rec.Code)
- }
- }
- func sendRequest(t *testing.T, body string, method string, URL string, resStatus int) *httptest.ResponseRecorder {
- router := startTestServer()
- respRec := httptest.NewRecorder()
- reqBody := bytes.NewReader([]byte(body))
- fmt.Println(URL)
- req, err := http.NewRequest(method, URL, reqBody)
- if err != nil {
- t.Fatal(err)
- }
- ctx = context.WithValue(ctx, transactionId.TransactionIDKey, "00000000-0000-0000-0000-000000000000")
- ctx = context.WithValue(ctx, modelMocks.IsNeedError, false)
- req = req.WithContext(ctx)
- router.ServeHTTP(respRec, req)
- t.Logf("Response: %s", string(respRec.Body.Bytes()))
- checkStatus(t, resStatus, respRec)
- if resStatus >= 400 {
- checkErrorMessage(t, respRec)
- }
- return respRec
- }
- func checkErrorMessage(t *testing.T, respRec *httptest.ResponseRecorder) {
- var act common.ErrorMessage
- recBody := respRec.Body.Bytes()
- if err := json.Unmarshal(recBody, &act); err != nil {
- t.Errorf("checkErrorMessage: can't unmarshall responce (err: %v)", err)
- }
- if act.Message == "" {
- t.Error("checkErrorMessage: empty error message")
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement