github.com/bshelton229/agent@v3.5.4+incompatible/agent/api_proxy_test.go (about)

     1  package agent
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"net/http/httptest"
     7  	"testing"
     8  )
     9  
    10  func TestAPIProxy(t *testing.T) {
    11  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    12  		if r.Header.Get(`Authorization`) != `Token llamas` {
    13  			http.Error(w, "Invalid authorization token", http.StatusUnauthorized)
    14  			return
    15  		}
    16  		fmt.Fprintln(w, `{"message": "ok"}`)
    17  	}))
    18  	defer ts.Close()
    19  
    20  	// create proxy to our fake api
    21  	proxy := NewAPIProxy(ts.URL, `llamas`)
    22  	go proxy.Listen()
    23  	proxy.Wait()
    24  	defer proxy.Close()
    25  
    26  	// create a client to talk to our proxy api
    27  	client := APIClient{
    28  		Endpoint: proxy.Endpoint(),
    29  		Token:    proxy.AccessToken(),
    30  	}.Create()
    31  
    32  	// fire a ping via the proxy
    33  	p, _, err := client.Pings.Get()
    34  	if err != nil {
    35  		t.Fatal(err)
    36  	}
    37  
    38  	if p.Message != `ok` {
    39  		t.Fatalf("Expected message to be `ok`, got %q", p.Message)
    40  	}
    41  }
    42  
    43  func TestAPIProxyFailsWithoutAccessToken(t *testing.T) {
    44  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    45  		if r.Header.Get(`Authorization`) != `Token llamas` {
    46  			http.Error(w, "Invalid authorization token", http.StatusUnauthorized)
    47  			return
    48  		}
    49  		fmt.Fprintln(w, `{"message": "ok"}`)
    50  	}))
    51  	defer ts.Close()
    52  
    53  	// create proxy to our fake api
    54  	proxy := NewAPIProxy(ts.URL, `llamas`)
    55  	go proxy.Listen()
    56  	proxy.Wait()
    57  	defer proxy.Close()
    58  
    59  	// create a client to talk to our proxy api, but with incorrect access token
    60  	client := APIClient{
    61  		Endpoint: proxy.Endpoint(),
    62  		Token:    `xxx`,
    63  	}.Create()
    64  
    65  	// fire a ping via the proxy
    66  	_, _, err := client.Pings.Get()
    67  	if err == nil {
    68  		t.Fatalf("Expected an error without an access token")
    69  	}
    70  }