github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/provider/azure/internal/azuretesting/senders.go (about)

     1  // Copyright 2015 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package azuretesting
     5  
     6  import (
     7  	"encoding/json"
     8  	"fmt"
     9  	"net/http"
    10  	"regexp"
    11  
    12  	"github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest"
    13  	"github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/mocks"
    14  )
    15  
    16  // MockSender is a wrapper around autorest/mocks.Sender, extending it with
    17  // request path checking to ease testing.
    18  type MockSender struct {
    19  	*mocks.Sender
    20  
    21  	// PathPattern, if non-empty, is assumed to be a regular expression
    22  	// that must match the request path.
    23  	PathPattern string
    24  }
    25  
    26  func (s *MockSender) Do(req *http.Request) (*http.Response, error) {
    27  	if s.PathPattern != "" {
    28  		matched, err := regexp.MatchString(s.PathPattern, req.URL.Path)
    29  		if err != nil {
    30  			return nil, err
    31  		}
    32  		if !matched {
    33  			return nil, fmt.Errorf(
    34  				"request path %q did not match pattern %q",
    35  				req.URL.Path, s.PathPattern,
    36  			)
    37  		}
    38  	}
    39  	return s.Sender.Do(req)
    40  }
    41  
    42  // NewSenderWithValue returns a *mocks.Sender that marshals the provided object
    43  // to JSON and sets it as the content. This function will panic if marshalling
    44  // fails.
    45  func NewSenderWithValue(v interface{}) *MockSender {
    46  	content, err := json.Marshal(v)
    47  	if err != nil {
    48  		panic(err)
    49  	}
    50  	sender := &MockSender{Sender: mocks.NewSender()}
    51  	sender.EmitContent(string(content))
    52  	return sender
    53  }
    54  
    55  // SequentialSender is a Sender that includes a collection of Senders, which
    56  // will be called in sequence.
    57  type Senders []autorest.Sender
    58  
    59  func (s *Senders) Do(req *http.Request) (*http.Response, error) {
    60  	if len(*s) == 0 {
    61  		response := mocks.NewResponseWithStatus("", http.StatusInternalServerError)
    62  		return response, fmt.Errorf("no sender for %q", req.URL)
    63  	}
    64  	sender := (*s)[0]
    65  	*s = (*s)[1:]
    66  	return sender.Do(req)
    67  }