github.com/ActiveState/cli@v0.0.0-20240508170324-6801f60cd051/internal/testhelpers/httpmock/httpmock_test.go (about)

     1  package httpmock
     2  
     3  import (
     4  	"io"
     5  	"net/http"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/require"
     9  
    10  	"github.com/stretchr/testify/assert"
    11  )
    12  
    13  var prefix = "http://test.tld/"
    14  
    15  func TestMock(t *testing.T) {
    16  	Activate(prefix)
    17  	defer DeActivate()
    18  
    19  	Register("GET", "test")
    20  	resp, err := http.Get(prefix + "test")
    21  	body, _ := io.ReadAll(resp.Body)
    22  	resp.Body.Close()
    23  	require.NoError(t, err, "Can call configured http mock")
    24  	assert.Equal(t, 200, resp.StatusCode)
    25  	assert.Equal(t, `{ "ok": true }`, string(body), "Returns the expected body")
    26  
    27  	RegisterWithCode("GET", "test", 501)
    28  	resp, err = http.Get(prefix + "test")
    29  	body, _ = io.ReadAll(resp.Body)
    30  	resp.Body.Close()
    31  	require.NoError(t, err, "Can call configured http mock")
    32  	assert.Equal(t, 501, resp.StatusCode)
    33  	assert.Equal(t, `{ "501": true }`, string(body), "Returns the expected body")
    34  
    35  	RegisterWithResponse("GET", "test", 501, "custom")
    36  	resp, err = http.Get(prefix + "test")
    37  	body, _ = io.ReadAll(resp.Body)
    38  	resp.Body.Close()
    39  	require.NoError(t, err, "Can call configured http mock")
    40  	assert.Equal(t, 501, resp.StatusCode)
    41  	assert.Equal(t, `{ "custom": true }`, string(body), "Returns the expected body")
    42  
    43  	RegisterWithResponseBody("GET", "test", 501, "body")
    44  	resp, err = http.Get(prefix + "test")
    45  	body, _ = io.ReadAll(resp.Body)
    46  	resp.Body.Close()
    47  	require.NoError(t, err, "Can call configured http mock")
    48  	assert.Equal(t, 501, resp.StatusCode)
    49  	assert.Equal(t, `body`, string(body), "Returns the expected body")
    50  
    51  	RegisterWithResponseBytes("GET", "test", 501, []byte("body"))
    52  	resp, err = http.Get(prefix + "test")
    53  	body, _ = io.ReadAll(resp.Body)
    54  	resp.Body.Close()
    55  	require.NoError(t, err, "Can call configured http mock")
    56  	assert.Equal(t, 501, resp.StatusCode)
    57  	assert.Equal(t, `body`, string(body), "Returns the expected body")
    58  }