github.com/m-lab/locate@v0.17.6/locatetest/locatetest.go (about)

     1  package locatetest
     2  
     3  import (
     4  	"log"
     5  	"net/http"
     6  	"net/http/httptest"
     7  	"net/url"
     8  	"strings"
     9  	"time"
    10  
    11  	"gopkg.in/square/go-jose.v2/jwt"
    12  
    13  	v2 "github.com/m-lab/locate/api/v2"
    14  	"github.com/m-lab/locate/clientgeo"
    15  	"github.com/m-lab/locate/handler"
    16  	"github.com/m-lab/locate/heartbeat"
    17  	prom "github.com/prometheus/client_golang/api/prometheus/v1"
    18  )
    19  
    20  // Signer implements the Signer interface for unit tests.
    21  type Signer struct{}
    22  
    23  // Sign creates a fake signature using the given claims.
    24  func (s *Signer) Sign(cl jwt.Claims) (string, error) {
    25  	t := strings.Join([]string{
    26  		cl.Audience[0], cl.Subject, cl.Issuer, cl.Expiry.Time().Format(time.RFC3339),
    27  	}, "--")
    28  	return t, nil
    29  }
    30  
    31  // LocatorV2 is a fake LocatorV2 implementation that returns the configured Servers or Err.
    32  type LocatorV2 struct {
    33  	heartbeat.StatusTracker
    34  	Servers []string
    35  	Err     error
    36  }
    37  
    38  // Nearest returns the pre-configured LocatorV2 Servers or Err.
    39  func (l *LocatorV2) Nearest(service string, lat, lon float64, opts *heartbeat.NearestOptions) (*heartbeat.TargetInfo, error) {
    40  	if l.Err != nil {
    41  		return nil, l.Err
    42  	}
    43  	t := make([]v2.Target, len(l.Servers))
    44  	for i := range l.Servers {
    45  		t[i].Machine = l.Servers[i]
    46  	}
    47  	return &heartbeat.TargetInfo{
    48  		Targets: t,
    49  		URLs:    []url.URL{},
    50  	}, nil
    51  }
    52  
    53  // NewLocateServerV2 creates an httptest.Server that can respond to Locate API V2
    54  // requests using a LocatorV2. Uselful for unit testing.
    55  func NewLocateServerV2(loc *LocatorV2) *httptest.Server {
    56  	// fake signer, fake locator.
    57  	s := &Signer{}
    58  	c := handler.NewClientDirect("fake-project", s, loc, &clientgeo.NullLocator{}, prom.NewAPI(nil))
    59  
    60  	// USER APIs
    61  	mux := http.NewServeMux()
    62  	mux.HandleFunc("/v2/nearest/", http.HandlerFunc(c.Nearest))
    63  
    64  	srv := httptest.NewServer(mux)
    65  	log.Println("Listening for INSECURE access requests on " + srv.URL)
    66  	return srv
    67  }