github.com/mendersoftware/go-lib-micro@v0.0.0-20240304135804-e8e39c59b148/requestid/client_test.go (about)

     1  // Copyright 2023 Northern.tech AS
     2  //
     3  //	Licensed under the Apache License, Version 2.0 (the "License");
     4  //	you may not use this file except in compliance with the License.
     5  //	You may obtain a copy of the License at
     6  //
     7  //	    http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  //	Unless required by applicable law or agreed to in writing, software
    10  //	distributed under the License is distributed on an "AS IS" BASIS,
    11  //	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  //	See the License for the specific language governing permissions and
    13  //	limitations under the License.
    14  package requestid
    15  
    16  import (
    17  	"net/http"
    18  	"net/http/httptest"
    19  	"testing"
    20  
    21  	"github.com/stretchr/testify/assert"
    22  )
    23  
    24  func TestNewTrackingApiClient(t *testing.T) {
    25  	c := NewTrackingApiClient("1234")
    26  	assert.NotNil(t, c)
    27  }
    28  
    29  func TestTrackingApiClientDo(t *testing.T) {
    30  	s := newMockServer()
    31  	defer s.Close()
    32  
    33  	c := NewTrackingApiClient("1234")
    34  	assert.NotNil(t, c)
    35  
    36  	req, err := http.NewRequest(
    37  		http.MethodGet, s.URL, nil)
    38  	assert.NoError(t, err)
    39  
    40  	rsp, err := c.Do(req)
    41  	assert.NotNil(t, rsp)
    42  
    43  	reqid := rsp.Header.Get(RequestIdHeader)
    44  	assert.Equal(t, "1234", reqid)
    45  }
    46  
    47  // mock server pings back the Request ID header
    48  func newMockServer() *httptest.Server {
    49  	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    50  		hdr := r.Header.Get(RequestIdHeader)
    51  		w.Header().Set(RequestIdHeader, hdr)
    52  		w.WriteHeader(200)
    53  	}))
    54  }