bitbucket.org/Aishee/synsec@v0.0.0-20210414005726-236fc01a153d/pkg/apiclient/client_test.go (about)

     1  package apiclient
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net/http"
     7  	"net/http/httptest"
     8  	"net/url"
     9  	"testing"
    10  
    11  	"github.com/stretchr/testify/assert"
    12  
    13  	"bitbucket.org/Aishee/synsec/pkg/cwversion"
    14  	log "github.com/sirupsen/logrus"
    15  )
    16  
    17  /*this is a ripoff of google/go-github approach :
    18  - setup a test http server along with a client that is configured to talk to test server
    19  - each test will then bind handler for the method(s) they want to try
    20  */
    21  
    22  func setup() (mux *http.ServeMux, serverURL string, teardown func()) {
    23  	// mux is the HTTP request multiplexer used with the test server.
    24  	mux = http.NewServeMux()
    25  	baseURLPath := "/v1"
    26  
    27  	apiHandler := http.NewServeMux()
    28  	apiHandler.Handle(baseURLPath+"/", http.StripPrefix(baseURLPath, mux))
    29  
    30  	// server is a test HTTP server used to provide mock API responses.
    31  	server := httptest.NewServer(apiHandler)
    32  
    33  	return mux, server.URL, server.Close
    34  }
    35  
    36  func testMethod(t *testing.T, r *http.Request, want string) {
    37  	t.Helper()
    38  	if got := r.Method; got != want {
    39  		t.Errorf("Request method: %v, want %v", got, want)
    40  	}
    41  }
    42  
    43  func TestNewClientOk(t *testing.T) {
    44  	mux, urlx, teardown := setup()
    45  	defer teardown()
    46  	apiURL, err := url.Parse(urlx + "/")
    47  	if err != nil {
    48  		log.Fatalf("parsing api url: %s", apiURL)
    49  	}
    50  	client, err := NewClient(&Config{
    51  		MachineID:     "test_login",
    52  		Password:      "test_password",
    53  		UserAgent:     fmt.Sprintf("synsec/%s", cwversion.VersionStr()),
    54  		URL:           apiURL,
    55  		VersionPrefix: "v1",
    56  	})
    57  	if err != nil {
    58  		t.Fatalf("new api client: %s", err.Error())
    59  	}
    60  	/*mock login*/
    61  	mux.HandleFunc("/watchers/login", func(w http.ResponseWriter, r *http.Request) {
    62  		w.WriteHeader(http.StatusOK)
    63  		w.Write([]byte(`{"code": 200, "expire": "2030-01-02T15:04:05Z", "token": "oklol"}`))
    64  	})
    65  
    66  	mux.HandleFunc("/alerts", func(w http.ResponseWriter, r *http.Request) {
    67  		testMethod(t, r, "GET")
    68  		w.WriteHeader(http.StatusOK)
    69  	})
    70  
    71  	_, resp, err := client.Alerts.List(context.Background(), AlertsListOpts{})
    72  	if err != nil {
    73  		t.Fatalf("test Unable to list alerts : %+v", err)
    74  	}
    75  	if resp.Response.StatusCode != http.StatusOK {
    76  		t.Fatalf("Alerts.List returned status: %d, want %d", resp.Response.StatusCode, http.StatusCreated)
    77  	}
    78  }
    79  
    80  func TestNewClientKo(t *testing.T) {
    81  	mux, urlx, teardown := setup()
    82  	defer teardown()
    83  	apiURL, err := url.Parse(urlx + "/")
    84  	if err != nil {
    85  		log.Fatalf("parsing api url: %s", apiURL)
    86  	}
    87  	client, err := NewClient(&Config{
    88  		MachineID:     "test_login",
    89  		Password:      "test_password",
    90  		UserAgent:     fmt.Sprintf("synsec/%s", cwversion.VersionStr()),
    91  		URL:           apiURL,
    92  		VersionPrefix: "v1",
    93  	})
    94  	if err != nil {
    95  		t.Fatalf("new api client: %s", err.Error())
    96  	}
    97  	/*mock login*/
    98  	mux.HandleFunc("/watchers/login", func(w http.ResponseWriter, r *http.Request) {
    99  		w.WriteHeader(http.StatusUnauthorized)
   100  		w.Write([]byte(`{"code": 401, "message" : "bad login/password"}`))
   101  	})
   102  
   103  	mux.HandleFunc("/alerts", func(w http.ResponseWriter, r *http.Request) {
   104  		testMethod(t, r, "GET")
   105  		w.WriteHeader(http.StatusOK)
   106  	})
   107  
   108  	_, _, err = client.Alerts.List(context.Background(), AlertsListOpts{})
   109  	assert.Contains(t, err.Error(), `received response status "401 Unauthorized"`)
   110  	log.Printf("err-> %s", err)
   111  }
   112  
   113  func TestNewDefaultClient(t *testing.T) {
   114  	mux, urlx, teardown := setup()
   115  	defer teardown()
   116  	apiURL, err := url.Parse(urlx + "/")
   117  	if err != nil {
   118  		log.Fatalf("parsing api url: %s", apiURL)
   119  	}
   120  	client, err := NewDefaultClient(apiURL, "/v1", "", nil)
   121  	if err != nil {
   122  		t.Fatalf("new api client: %s", err.Error())
   123  	}
   124  	mux.HandleFunc("/alerts", func(w http.ResponseWriter, r *http.Request) {
   125  		w.WriteHeader(http.StatusUnauthorized)
   126  		w.Write([]byte(`{"code": 401, "message" : "brr"}`))
   127  	})
   128  	_, _, err = client.Alerts.List(context.Background(), AlertsListOpts{})
   129  	assert.Contains(t, err.Error(), `performing request: API error: brr`)
   130  	log.Printf("err-> %s", err)
   131  }
   132  
   133  func TestNewClientRegisterKO(t *testing.T) {
   134  	apiURL, err := url.Parse("http://127.0.0.1:4242/")
   135  	if err != nil {
   136  		t.Fatalf("parsing api url: %s", apiURL)
   137  	}
   138  	_, err = RegisterClient(&Config{
   139  		MachineID:     "test_login",
   140  		Password:      "test_password",
   141  		UserAgent:     fmt.Sprintf("synsec/%s", cwversion.VersionStr()),
   142  		URL:           apiURL,
   143  		VersionPrefix: "v1",
   144  	}, &http.Client{})
   145  	assert.Contains(t, fmt.Sprintf("%s", err), "dial tcp 127.0.0.1:4242: connect: connection refused")
   146  }
   147  
   148  func TestNewClientRegisterOK(t *testing.T) {
   149  	log.SetLevel(log.TraceLevel)
   150  	mux, urlx, teardown := setup()
   151  	defer teardown()
   152  
   153  	/*mock login*/
   154  	mux.HandleFunc("/watchers", func(w http.ResponseWriter, r *http.Request) {
   155  		testMethod(t, r, "POST")
   156  		w.WriteHeader(http.StatusOK)
   157  		w.Write([]byte(`{"code": 200, "expire": "2030-01-02T15:04:05Z", "token": "oklol"}`))
   158  	})
   159  
   160  	apiURL, err := url.Parse(urlx + "/")
   161  	if err != nil {
   162  		t.Fatalf("parsing api url: %s", apiURL)
   163  	}
   164  	client, err := RegisterClient(&Config{
   165  		MachineID:     "test_login",
   166  		Password:      "test_password",
   167  		UserAgent:     fmt.Sprintf("synsec/%s", cwversion.VersionStr()),
   168  		URL:           apiURL,
   169  		VersionPrefix: "v1",
   170  	}, &http.Client{})
   171  	if err != nil {
   172  		t.Fatalf("while registering client : %s", err)
   173  	}
   174  	log.Printf("->%T", client)
   175  }
   176  
   177  func TestNewClientBadAnswer(t *testing.T) {
   178  	log.SetLevel(log.TraceLevel)
   179  	mux, urlx, teardown := setup()
   180  	defer teardown()
   181  
   182  	/*mock login*/
   183  	mux.HandleFunc("/watchers", func(w http.ResponseWriter, r *http.Request) {
   184  		testMethod(t, r, "POST")
   185  		w.WriteHeader(http.StatusUnauthorized)
   186  		w.Write([]byte(`bad`))
   187  	})
   188  	apiURL, err := url.Parse(urlx + "/")
   189  	if err != nil {
   190  		t.Fatalf("parsing api url: %s", apiURL)
   191  	}
   192  	_, err = RegisterClient(&Config{
   193  		MachineID:     "test_login",
   194  		Password:      "test_password",
   195  		UserAgent:     fmt.Sprintf("synsec/%s", cwversion.VersionStr()),
   196  		URL:           apiURL,
   197  		VersionPrefix: "v1",
   198  	}, &http.Client{})
   199  	assert.Contains(t, fmt.Sprintf("%s", err), `invalid body: invalid character 'b' looking for beginning of value`)
   200  }