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

     1  package apiclient
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net/http"
     7  	"net/url"
     8  	"testing"
     9  	"time"
    10  
    11  	"bitbucket.org/Aishee/synsec/pkg/cwversion"
    12  	log "github.com/sirupsen/logrus"
    13  	"github.com/stretchr/testify/assert"
    14  )
    15  
    16  func TestNewRequestInvalid(t *testing.T) {
    17  	mux, urlx, teardown := setup()
    18  	defer teardown()
    19  	//missing slash in uri
    20  	apiURL, err := url.Parse(urlx)
    21  	if err != nil {
    22  		log.Fatalf("parsing api url: %s", apiURL)
    23  	}
    24  	client, err := NewClient(&Config{
    25  		MachineID:     "test_login",
    26  		Password:      "test_password",
    27  		UserAgent:     fmt.Sprintf("synsec/%s", cwversion.VersionStr()),
    28  		URL:           apiURL,
    29  		VersionPrefix: "v1",
    30  	})
    31  	if err != nil {
    32  		t.Fatalf("new api client: %s", err.Error())
    33  	}
    34  	/*mock login*/
    35  	mux.HandleFunc("/watchers/login", func(w http.ResponseWriter, r *http.Request) {
    36  		w.WriteHeader(http.StatusUnauthorized)
    37  		w.Write([]byte(`{"code": 401, "message" : "bad login/password"}`))
    38  	})
    39  
    40  	mux.HandleFunc("/alerts", func(w http.ResponseWriter, r *http.Request) {
    41  		testMethod(t, r, "GET")
    42  		w.WriteHeader(http.StatusOK)
    43  	})
    44  
    45  	_, _, err = client.Alerts.List(context.Background(), AlertsListOpts{})
    46  	assert.Contains(t, err.Error(), `building request: BaseURL must have a trailing slash, but `)
    47  }
    48  
    49  func TestNewRequestTimeout(t *testing.T) {
    50  	mux, urlx, teardown := setup()
    51  	defer teardown()
    52  	//missing slash in uri
    53  	apiURL, err := url.Parse(urlx + "/")
    54  	if err != nil {
    55  		log.Fatalf("parsing api url: %s", apiURL)
    56  	}
    57  	client, err := NewClient(&Config{
    58  		MachineID:     "test_login",
    59  		Password:      "test_password",
    60  		UserAgent:     fmt.Sprintf("synsec/%s", cwversion.VersionStr()),
    61  		URL:           apiURL,
    62  		VersionPrefix: "v1",
    63  	})
    64  	if err != nil {
    65  		t.Fatalf("new api client: %s", err.Error())
    66  	}
    67  	/*mock login*/
    68  	mux.HandleFunc("/watchers/login", func(w http.ResponseWriter, r *http.Request) {
    69  		time.Sleep(2 * time.Second)
    70  	})
    71  
    72  	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
    73  	defer cancel()
    74  
    75  	_, _, err = client.Alerts.List(ctx, AlertsListOpts{})
    76  	assert.Contains(t, err.Error(), `performing request: context deadline exceeded`)
    77  }