Advertisement
Guest User

Untitled

a guest
Nov 8th, 2017
406
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 10.07 KB | None | 0 0
  1. package execution
  2.  
  3. import (
  4.     "bytes"
  5.     "context"
  6.     "encoding/base64"
  7.     "encoding/json"
  8.     "fmt"
  9.     apiModels "github.com/ContinuumLLC/platform-api-model/clients/model/Golang/resourceModel/tasking"
  10.     "github.com/ContinuumLLC/platform-scripting-service/src/app-loader"
  11.     "github.com/ContinuumLLC/platform-scripting-service/src/middlewares/transaction-id"
  12.     "github.com/ContinuumLLC/platform-scripting-service/src/model-mocks"
  13.     "github.com/ContinuumLLC/platform-scripting-service/src/models"
  14.     "github.com/ContinuumLLC/platform-scripting-service/src/services/common"
  15.     "github.com/gocql/gocql"
  16.     "github.com/gorilla/mux"
  17.     "github.com/pkg/errors"
  18.     "net/http"
  19.     "net/http/httptest"
  20.     "reflect"
  21.     "strings"
  22.     "testing"
  23.     "time"
  24. )
  25.  
  26. const (
  27.     baseURL                 = "/ss/v1/partners"
  28.     postExecutionPayloadURL = baseURL + "/{partnerID}/execute"
  29. )
  30.  
  31. var (
  32.     ctx            context.Context
  33.     service        Service
  34.     scriptRepo     models.ScriptingPersistence
  35.     executionsRepo models.ExecutionPersistence
  36.  
  37.     testTransactionID, _ = gocql.ParseUUID("00000000-0000-0000-0000-000000000022")
  38. )
  39.  
  40. func init() {
  41.     appLoader.LoadApplicationServices(true)
  42. }
  43.  
  44. func setUp(fillScriptMock, fillExectuionsMock bool) {
  45.     scriptRepo = modelMocks.NewScriptRepoMock(fillScriptMock)
  46.     executionMock := modelMocks.NewExectuionRepoMock(fillExectuionsMock)
  47.     service = NewService(scriptRepo, executionMock)
  48.     ctx = context.WithValue(ctx, transactionId.TransactionIDKey, testTransactionID)
  49. }
  50.  
  51. func tireDown() {
  52. }
  53.  
  54. func TestRunExecutionWithEmptyPayload(t *testing.T) {
  55.     setUp(true, false)
  56.     defer tireDown()
  57.  
  58.     sendRequest(t, string(""), "POST", postExecutionPayloadURL, 500)
  59. }
  60.  
  61. func TestInsertParametersIntoScriptBody(t *testing.T) {
  62.  
  63.     tests := []struct {
  64.         parameters     string
  65.         expectedResult []string
  66.     }{
  67.         {
  68.             `{ "force" : false, "userName": "Name1", "int":1, "float":1.1,"array":[ "Ford", "BMW", "Fiat" ], "floatArray":[1.1,2.2,3.3]}`,
  69.             []string{"$force=$false", `$userName="Name1"`, "$int=1", "$float=1.1", "$array=\"Ford\",\"BMW\",\"Fiat\"", "$floatArray=1.1,2.2,3.3"},
  70.         },
  71.     }
  72.  
  73.     for _, test := range tests {
  74.         scriptBody, err := addParametersToTheBeginnigOfScriptBody(test.parameters, "someScript")
  75.  
  76.         if err != nil {
  77.             t.Fatalf("Incorrect result. error %v", err)
  78.         }
  79.  
  80.         for _, expected := range test.expectedResult {
  81.             if !strings.Contains(scriptBody, expected) {
  82.                 t.Fatalf("Incorrect result. expected %v but obtained %v", expected, scriptBody)
  83.             }
  84.         }
  85.     }
  86. }
  87.  
  88. func TestValidateJob(t *testing.T) {
  89.     uuid := "12940ab9-f577-4c73-ac26-2a7ed56e6615"
  90.     var payloads []apiModels.ExecutionPayload
  91.     payloads = append(payloads, apiModels.ExecutionPayload{
  92.         Parameters:        "",
  93.         ManagedEndpointID: uuid,
  94.         OriginID:          uuid,
  95.         ExecutionID:       uuid,
  96.         HookURL:           "http://someURL",
  97.     }, apiModels.ExecutionPayload{
  98.         Parameters:        `{"name":"UserName1", "password":"paswd123"}`,
  99.         ManagedEndpointID: uuid,
  100.         OriginID:          uuid,
  101.         ExecutionID:       uuid,
  102.         HookURL:           "http://someURL",
  103.     })
  104.     err := validateJob(payloads)
  105.     if err != nil {
  106.         t.Fatalf("Error:%v", err)
  107.     }
  108.  
  109. }
  110. func TestValidateJobException(t *testing.T) {
  111.     uuid := "12940ab9-f577-4c73-ac26-2a7ed56e6615"
  112.     var payloads []apiModels.ExecutionPayload
  113.     payloads = append(payloads, apiModels.ExecutionPayload{
  114.         Parameters:        "",
  115.         ExecutionID:       "",
  116.         OriginID:          uuid,
  117.         ManagedEndpointID: uuid,
  118.         HookURL:           "http://someURL",
  119.     })
  120.     err := validateJob(payloads)
  121.     if err == nil {
  122.         t.Fatal("Error should not be nil when ExecutionPayload.ExecutionID is empty")
  123.     }
  124. }
  125.  
  126. func TestCreateExecutionMessage(t *testing.T) {
  127.     var payload apiModels.ExecutionPayload
  128.     var script apiModels.Script
  129.     var executionMessage models.ExecutionMessage
  130.     var err error
  131.  
  132.     uuid := "12940ab9-f577-4c73-ac26-2a7ed56e6615"
  133.     payload = apiModels.ExecutionPayload{
  134.         Parameters:        `{"name":"UserName1", "password":"paswd123"}`,
  135.         ManagedEndpointID: uuid,
  136.         OriginID:          uuid,
  137.         ExecutionID:       uuid,
  138.         HookURL:           "http://someURL",
  139.     }
  140.  
  141.     timeNow := time.Now()
  142.     script = apiModels.Script{
  143.         CreatedAt:   timeNow,
  144.         ID:          uuid,
  145.         Engine:      "engine",
  146.         Content:     "Z3B1cGRhdGUgL2ZvcmNl",
  147.         Name:        "name",
  148.         Description: "description",
  149.         Categories:  []string{"patch", "script"},
  150.         PartnerID:   "507231",
  151.     }
  152.     executionMessage, err = createExecutionMessage(payload, script)
  153.     if err != nil {
  154.         t.Errorf("Error:%v", err)
  155.     }
  156.  
  157.     schedule := "SCHEDULE"
  158.     if executionMessage.Type != schedule {
  159.         t.Errorf("Incorrect type %v expected %v", executionMessage.Type, schedule)
  160.     }
  161.  
  162.     version := "1.0"
  163.     if executionMessage.Version != version {
  164.         t.Errorf("Incorrect Version %v expected %v", executionMessage.Version, version)
  165.     }
  166.  
  167.     path := "/scripting/scripting/command"
  168.     if executionMessage.Path != path {
  169.         t.Errorf("Incorrect path %v expected %v", executionMessage.Path, path)
  170.     }
  171.  
  172.     var m models.Message
  173.     err = json.Unmarshal([]byte(executionMessage.Message), &m)
  174.     if err != nil {
  175.         t.Errorf("Error %v while unmarshal message %v", err, executionMessage.Message)
  176.     }
  177.     task := "/schedule/"
  178.     if m.Task != task {
  179.         t.Errorf("Incorrect task %v expected %v", m.Task, task)
  180.     }
  181.  
  182.     if m.ExecuteNow != "true" {
  183.         t.Errorf("Incorrect executeNow %v expected %v", m.ExecuteNow, true)
  184.     }
  185.  
  186.     if m.Schedule != "" {
  187.         t.Errorf("Incorrect schedule %v expected %v", m.Schedule, "")
  188.     }
  189.  
  190.     taskInputBin, err := base64.StdEncoding.DecodeString(m.TaskInput)
  191.     if err != nil {
  192.         t.Fatalf("Can't decode task input from Base64: %v", err)
  193.     }
  194.  
  195.     var taskInput models.TaskInput
  196.     err = json.Unmarshal(taskInputBin, &taskInput)
  197.     if err != nil {
  198.         t.Fatalf("Can't decode task input from JSON: %v", err)
  199.     }
  200.  
  201.     if taskInput.ExecutionID.String() != uuid {
  202.         t.Errorf("Incorrect ExecutionID %v expected %v", taskInput.ExecutionID, uuid)
  203.     }
  204.  
  205.     if !strings.Contains(taskInput.Script.Body, "$password=\"paswd123\"") || !strings.Contains(taskInput.Script.Body, "$name=\"UserName1\"") {
  206.         t.Errorf("Incorrect taskInput.Script: absence of some of parameters")
  207.     }
  208.  
  209.     if !strings.Contains(taskInput.Script.Body, "gpupdate /force") {
  210.         t.Errorf("Incorrect taskInput.Script: absence of script body")
  211.     }
  212.     if taskInput.Script.Executor != "engine" {
  213.         t.Errorf("Incorrect taskInput.Script.Executor %v expected engine", taskInput.Script.Executor)
  214.     }
  215. }
  216.  
  217. func TestRunExecutionEmptyPayload(t *testing.T) {
  218.     setUp(true, false)
  219.     defer tireDown()
  220.     sendRequest(t,
  221.         string(`[]`),
  222.         "POST", "/ss/v1/partners/123456789/execute", 400)
  223.  
  224. }
  225.  
  226. func TestAddValueToBuffer(t *testing.T) {
  227.     tests := []struct {
  228.         values         []interface{}
  229.         expectedResult string
  230.     }{
  231.         {
  232.             values:         []interface{}{"param1", 22, true},
  233.             expectedResult: "\"param1\"22$true",
  234.         },
  235.         {
  236.             values:         []interface{}{"username@gmail.com", "password#@$true", 3.14, "zd", 2.718, "c"},
  237.             expectedResult: `"username@gmail.com""password#@$true"3.14"zd"2.718"c"`,
  238.         },
  239.     }
  240.     for _, test := range tests {
  241.         buffer := &bytes.Buffer{}
  242.         for _, value := range test.values {
  243.             addValueToBuffer(buffer, value)
  244.         }
  245.         if buffer.String() != test.expectedResult {
  246.             t.Fatalf("Expected %s, but got %s", test.expectedResult, buffer.String())
  247.         }
  248.     }
  249. }
  250.  
  251. func TestExtractPayload(t *testing.T) {
  252.     payload := apiModels.ExecutionPayload{
  253.         ExecutionID:       "ExecutionID",
  254.         ManagedEndpointID: "ManagedEndpointID",
  255.         HookURL:           "http://loclahost",
  256.         OriginID:          "OriginID",
  257.         Parameters:        "paramaters-bla-bla-bla",
  258.     }
  259.     payloadBin, _ := json.Marshal([]apiModels.ExecutionPayload{payload})
  260.     tests := []struct {
  261.         requestBody    string
  262.         requestMethod  string
  263.         expectedResult []apiModels.ExecutionPayload
  264.         err            error
  265.     }{
  266.         {
  267.             requestMethod: "POST",
  268.             requestBody:   "aaa",
  269.             err:           errors.New("Can't unmarshal input data: aaa (err: invalid character 'a' looking for beginning of value)"),
  270.         },
  271.         {
  272.             requestMethod:  "POST",
  273.             requestBody:    string(payloadBin),
  274.             expectedResult: []apiModels.ExecutionPayload{payload},
  275.         },
  276.     }
  277.  
  278.     for _, test := range tests {
  279.         req, err := http.NewRequest(test.requestMethod, "http://localhost", bytes.NewReader([]byte(test.requestBody)))
  280.         if err != nil {
  281.             t.Fatalf("Can't create request, err: %v", err)
  282.         }
  283.  
  284.         actualPayload, err := extractPayload(req)
  285.  
  286.         if err != nil && test.err != nil && (err.Error() != test.err.Error()) {
  287.             t.Fatalf("Expected error %v, but got %v", test.err, err)
  288.         }
  289.  
  290.         if !reflect.DeepEqual(actualPayload, test.expectedResult) {
  291.             t.Fatalf("Expected result %v, but got %v", test.expectedResult, actualPayload)
  292.         }
  293.     }
  294. }
  295.  
  296. // =================Internal functions===========================
  297.  
  298. func startTestServer() *mux.Router {
  299.     router := mux.NewRouter()
  300.     router.HandleFunc(postExecutionPayloadURL, http.HandlerFunc(service.RunExecution)).Methods("POST")
  301.     return router
  302. }
  303.  
  304. func checkStatus(t *testing.T, status int, rec *httptest.ResponseRecorder) {
  305.     if rec.Code != status {
  306.         t.Fatalf("expected the status %d but got %d\n", status, rec.Code)
  307.     }
  308. }
  309.  
  310. func sendRequest(t *testing.T, body string, method string, URL string, resStatus int) *httptest.ResponseRecorder {
  311.     router := startTestServer()
  312.     respRec := httptest.NewRecorder()
  313.  
  314.     reqBody := bytes.NewReader([]byte(body))
  315.     fmt.Println(URL)
  316.     req, err := http.NewRequest(method, URL, reqBody)
  317.  
  318.     if err != nil {
  319.         t.Fatal(err)
  320.     }
  321.  
  322.     ctx = context.WithValue(ctx, transactionId.TransactionIDKey, "00000000-0000-0000-0000-000000000000")
  323.     ctx = context.WithValue(ctx, modelMocks.IsNeedError, false)
  324.  
  325.     req = req.WithContext(ctx)
  326.     router.ServeHTTP(respRec, req)
  327.     t.Logf("Response: %s", string(respRec.Body.Bytes()))
  328.     checkStatus(t, resStatus, respRec)
  329.  
  330.     if resStatus >= 400 {
  331.         checkErrorMessage(t, respRec)
  332.     }
  333.  
  334.     return respRec
  335. }
  336.  
  337. func checkErrorMessage(t *testing.T, respRec *httptest.ResponseRecorder) {
  338.     var act common.ErrorMessage
  339.     recBody := respRec.Body.Bytes()
  340.     if err := json.Unmarshal(recBody, &act); err != nil {
  341.         t.Errorf("checkErrorMessage: can't unmarshall responce (err: %v)", err)
  342.     }
  343.  
  344.     if act.Message == "" {
  345.         t.Error("checkErrorMessage: empty error message")
  346.     }
  347. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement