github.com/waldiirawan/apm-agent-go/v2@v2.2.2/transport/util_test.go (about)

     1  // Licensed to Elasticsearch B.V. under one or more contributor
     2  // license agreements. See the NOTICE file distributed with
     3  // this work for additional information regarding copyright
     4  // ownership. Elasticsearch B.V. licenses this file to you under
     5  // the Apache License, Version 2.0 (the "License"); you may
     6  // not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  //     http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing,
    12  // software distributed under the License is distributed on an
    13  // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    14  // KIND, either express or implied.  See the License for the
    15  // specific language governing permissions and limitations
    16  // under the License.
    17  
    18  package transport_test
    19  
    20  import (
    21  	"bytes"
    22  	"io"
    23  	"io/ioutil"
    24  	"net/http"
    25  	"os"
    26  	"sync"
    27  	"testing"
    28  
    29  	"github.com/stretchr/testify/assert"
    30  )
    31  
    32  type nopHandler struct{}
    33  
    34  func (nopHandler) ServeHTTP(http.ResponseWriter, *http.Request) {}
    35  
    36  type recordingHandler struct {
    37  	mu       sync.Mutex
    38  	requests []*http.Request
    39  }
    40  
    41  func (h *recordingHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    42  	h.mu.Lock()
    43  	defer h.mu.Unlock()
    44  
    45  	var buf bytes.Buffer
    46  	_, err := io.Copy(&buf, req.Body)
    47  	if err != nil {
    48  		panic(err)
    49  	}
    50  	req.Body = ioutil.NopCloser(&buf)
    51  	h.requests = append(h.requests, req)
    52  }
    53  
    54  func assertAuthorization(t *testing.T, req *http.Request, expect ...string) {
    55  	values, ok := req.Header["Authorization"]
    56  	if ok && len(expect) == 0 {
    57  		t.Errorf("unexpected Authorization header")
    58  		return
    59  	}
    60  	if !ok && len(expect) != 0 {
    61  		t.Errorf("missing Authorization header")
    62  		return
    63  	}
    64  	assert.Equal(t, expect, values)
    65  }
    66  
    67  func patchEnv(key, value string) func() {
    68  	old, had := os.LookupEnv(key)
    69  	if err := os.Setenv(key, value); err != nil {
    70  		panic(err)
    71  	}
    72  	return func() {
    73  		var err error
    74  		if !had {
    75  			err = os.Unsetenv(key)
    76  		} else {
    77  			err = os.Setenv(key, old)
    78  		}
    79  		if err != nil {
    80  			panic(err)
    81  		}
    82  	}
    83  }