Bläddra i källkod

begin test for api

AlteredCoder 5 år sedan
förälder
incheckning
72ff2fbc12
4 ändrade filer med 117 tillägg och 17 borttagningar
  1. 3 4
      pkg/acquisition/file_reader_test.go
  2. 9 13
      pkg/cwapi/auth.go
  3. 95 0
      pkg/cwapi/auth_test.go
  4. 10 0
      pkg/cwapi/tests/api_config.yaml

+ 3 - 4
pkg/acquisition/file_reader_test.go

@@ -14,10 +14,9 @@ func TestLoadAcquisitionConfig(t *testing.T) {
 	testFilePath := "./tests/test.log"
 
 	tests := []struct {
-		csConfig   *csconfig.CrowdSec
-		result     *FileAcquisCtx
-		err        string
-		assertFunc interface{}
+		csConfig *csconfig.CrowdSec
+		result   *FileAcquisCtx
+		err      string
 	}{
 		{
 			csConfig: &csconfig.CrowdSec{

+ 9 - 13
pkg/cwapi/auth.go

@@ -96,7 +96,9 @@ func (ctx *ApiCtx) LoadConfig(cfg string) error {
 		log.Warningf("!API paths must not be prefixed by /")
 	}
 
-	ctx.Http = sling.New().Base(ctx.BaseURL+"/"+ctx.ApiVersion+"/").Set("User-Agent", fmt.Sprintf("Crowdsec/%s", cwversion.VersionStr()))
+	httpClient := &http.Client{Timeout: 20 * time.Second}
+
+	ctx.Http = sling.New().Client(httpClient).Base(ctx.BaseURL+"/"+ctx.ApiVersion+"/").Set("User-Agent", fmt.Sprintf("Crowdsec/%s", cwversion.VersionStr()))
 	log.Printf("api load configuration: configuration loaded successfully (base:%s)", ctx.BaseURL+"/"+ctx.ApiVersion+"/")
 	return nil
 }
@@ -139,17 +141,13 @@ func (ctx *ApiCtx) Signin() error {
 	if ctx.Creds.User == "" || ctx.Creds.Password == "" {
 		return fmt.Errorf("api signin: missing credentials in api.yaml")
 	}
+	jsonResp := &ApiResp{}
 
-	req, err := ctx.Http.New().Post(ctx.SigninPath).BodyJSON(ctx.Creds).Request()
+	resp, err := ctx.Http.Post(ctx.SigninPath).BodyJSON(ctx.Creds).ReceiveSuccess(jsonResp)
 	if err != nil {
 		return fmt.Errorf("api signin: HTTP request creation failed: %s", err)
 	}
-	log.Debugf("api signin: URL: '%s'", req.URL)
-	httpClient := http.Client{Timeout: 20 * time.Second}
-	resp, err := httpClient.Do(req)
-	if err != nil {
-		return fmt.Errorf("api signin: API call failed : %s", err)
-	}
+
 	defer resp.Body.Close()
 	body, err := ioutil.ReadAll(resp.Body)
 	if err != nil {
@@ -159,12 +157,10 @@ func (ctx *ApiCtx) Signin() error {
 	if resp.StatusCode != 200 {
 		return fmt.Errorf("api signin: return bad HTTP code (%d): %s", resp.StatusCode, string(body))
 	}
-
-	jsonResp := ApiResp{}
-	err = json.Unmarshal(body, &jsonResp)
-	if err != nil {
-		return fmt.Errorf("api signin: unable to unmarshall api response '%s': %s", string(body), err.Error())
+	if jsonResp.Message == "" || jsonResp.StatusCode != 200 {
+		return fmt.Errorf("api signin failed. http response: %s", body)
 	}
+
 	ctx.Http = ctx.Http.Set("Authorization", jsonResp.Message)
 	log.Printf("api signin: signed in successfuly")
 	return nil

+ 95 - 0
pkg/cwapi/auth_test.go

@@ -0,0 +1,95 @@
+package cwapi
+
+import (
+	"fmt"
+	"io/ioutil"
+	"net/http"
+	"strings"
+	"testing"
+
+	"github.com/dghubble/sling"
+	"gopkg.in/tomb.v2"
+)
+
+const configFile = "./tests/api_config.yaml"
+const apiVersion = "v1"
+const apiURL = "https://my_test_endpoint"
+
+var apiBaseURL = fmt.Sprintf("%s/%s/", apiURL, apiVersion)
+
+var httpClientMock = &http.Client{
+	Transport: newMockTransport(),
+}
+
+type mockTransport struct{}
+
+func newMockTransport() http.RoundTripper {
+	return &mockTransport{}
+}
+
+// Implement http.RoundTripper
+func (t *mockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+	var responseBody string
+	var statusCode int
+	// Create mocked http.Response
+	response := &http.Response{
+		Header:  make(http.Header),
+		Request: req,
+	}
+	response.Header.Set("Content-Type", "application/json")
+	if req.URL.Path == "/v1/signin" {
+		responseBody = `{"statusCode": 200, "message": "crowdsec_api_token"}`
+		statusCode = 200
+	}
+	response.StatusCode = statusCode
+	response.Body = ioutil.NopCloser(strings.NewReader(responseBody))
+	return response, nil
+}
+
+func TestSignin(t *testing.T) {
+
+	tests := []struct {
+		apiCtx *ApiCtx
+		err    error
+	}{
+		{
+			apiCtx: &ApiCtx{
+				ApiVersion:   "v1",
+				PullPath:     "pull",
+				PushPath:     "signals",
+				SigninPath:   "signin",
+				RegisterPath: "register",
+				ResetPwdPath: "resetpassword",
+				EnrollPath:   "enroll",
+				BaseURL:      "https://my_testendpoint.com",
+				CfgUser:      "machine_id",
+				CfgPassword:  "machine_password",
+				Creds: ApiCreds{
+					User:     "machine_id",
+					Password: "machine_password",
+					Profile:  "crowdsec/test1,crowdsec/test2",
+				},
+				Muted:      false,
+				DebugDump:  false,
+				Http:       sling.New().Client(httpClientMock).Base(apiBaseURL),
+				PusherTomb: tomb.Tomb{},
+			},
+		},
+	}
+
+	for _, test := range tests {
+		if err := test.apiCtx.Signin(); err != nil {
+			t.Fatalf(err.Error())
+		}
+	}
+
+}
+
+/*func TestRegister(t *testing.T) {
+	prepTest()
+
+	if err := apiCtx.RegisterMachine(); err != nil {
+		t.Fatalf(err.Error())
+	}
+}
+*/

+ 10 - 0
pkg/cwapi/tests/api_config.yaml

@@ -0,0 +1,10 @@
+version: v1
+url: https://test_endpoint
+signin_path: signin
+push_path: signals
+pull_path: pull
+enroll_path: enroll
+reset_pwd_path: resetpassword
+register_path: register
+machine_id: test
+password: test