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

     1  // Package clientgeo supports interfaces to different data sources to help
     2  // identify client geo location for server selection.
     3  package clientgeo
     4  
     5  import (
     6  	"context"
     7  	"errors"
     8  	"net/http"
     9  	"net/http/httptest"
    10  	"reflect"
    11  	"testing"
    12  )
    13  
    14  func TestNullLocator_Locate(t *testing.T) {
    15  	nl := &NullLocator{}
    16  	req := httptest.NewRequest(http.MethodGet, "/anyurl", nil)
    17  	nl.Reload(context.Background())
    18  	l, err := nl.Locate(req)
    19  	if err != nil {
    20  		t.Fatalf("NullLocator.Locate return an err; %v", err)
    21  	}
    22  	if l.Latitude != "0.000000" && l.Longitude != "0.000000" {
    23  		t.Fatalf("NullLocator.Location has wrong values; want: 0.000000,0.000000 got: %#v", l)
    24  	}
    25  }
    26  
    27  type errLocator struct{}
    28  
    29  func (e *errLocator) Locate(req *http.Request) (*Location, error) {
    30  	return nil, errors.New("error")
    31  }
    32  
    33  func (e *errLocator) Reload(ctx context.Context) {}
    34  
    35  func TestMultiLocator(t *testing.T) {
    36  	want := &Location{
    37  		Latitude:  "0.000000",
    38  		Longitude: "0.000000",
    39  	}
    40  	t.Run("success", func(t *testing.T) {
    41  		ml := MultiLocator{&errLocator{}, &NullLocator{}}
    42  		req := httptest.NewRequest(http.MethodGet, "/anyurl", nil)
    43  		l, err := ml.Locate(req)
    44  		if err != nil {
    45  			t.Errorf("MultiLocator.Locate returned error: %v", err)
    46  		}
    47  		if !reflect.DeepEqual(l, want) {
    48  			t.Errorf("MultiLocator() = %v, want %v", l, want)
    49  		}
    50  		ml.Reload(req.Context())
    51  	})
    52  	t.Run("all-errors", func(t *testing.T) {
    53  		ml := MultiLocator{&errLocator{}, &errLocator{}}
    54  		req := httptest.NewRequest(http.MethodGet, "/anyurl", nil)
    55  		_, err := ml.Locate(req)
    56  		if err == nil {
    57  			t.Errorf("MultiLocator.Locate should return error: got nil")
    58  		}
    59  	})
    60  }