github.com/pf-qiu/concourse/v6@v6.7.3-0.20201207032516-1f455d73275f/atc/testhelpers/http_header_matcher.go (about)

     1  package testhelpers
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"github.com/onsi/gomega/types"
     7  	"net/http"
     8  )
     9  
    10  func IncludeHeaderEntries(expected map[string]string) types.GomegaMatcher {
    11  	return &includeHeaderEntries{
    12  		expected: expected,
    13  	}
    14  }
    15  
    16  type includeHeaderEntries struct {
    17  	expected map[string]string
    18  }
    19  
    20  func (h includeHeaderEntries) Match(actual interface{}) (bool, error) {
    21  	actualResponse, ok := actual.(*http.Response)
    22  	if !ok {
    23  		return false, fmt.Errorf("IncludeHeaderEntries matcher expects a *http.Response but got %T", actual)
    24  	}
    25  	return h.matchHeaderEntries(actualResponse.Header)
    26  }
    27  
    28  func (h includeHeaderEntries) matchHeaderEntries(header http.Header) (success bool, err error) {
    29  	for expectedKey, expectedVal := range h.expected {
    30  
    31  		_, keyFound := header[expectedKey]
    32  		if !keyFound {
    33  			return false, err
    34  		}
    35  
    36  		actualVal := header.Get(expectedKey)
    37  		if expectedVal != actualVal {
    38  			return false, err
    39  		}
    40  	}
    41  
    42  	return true, nil
    43  }
    44  
    45  func (h includeHeaderEntries) FailureMessage(actual interface{}) (message string) {
    46  	actualResponse, _ := actual.(*http.Response)
    47  	bytes, _ := json.Marshal(actualResponse.Header)
    48  	actualHeaders := string(bytes)
    49  
    50  	bytes, _ = json.Marshal(h.expected)
    51  	expectedHeaders := string(bytes)
    52  
    53  	return fmt.Sprintf("Expected http response header\n\t%s\nto include headers\n\t%s", actualHeaders, expectedHeaders)
    54  }
    55  
    56  func (h includeHeaderEntries) NegatedFailureMessage(actual interface{}) (message string) {
    57  	actualResponse, _ := actual.(*http.Response)
    58  	bytes, _ := json.Marshal(actualResponse.Header)
    59  	actualHeaders := string(bytes)
    60  
    61  	bytes, _ = json.Marshal(h.expected)
    62  	expectedHeaders := string(bytes)
    63  
    64  	return fmt.Sprintf("Expected http response header\n\t%s\nto not include headers\n\t%s", actualHeaders, expectedHeaders)
    65  }