github.com/go-playground/pkg/v5@v5.29.1/net/http/helpers_test_go1.18.go (about)

     1  //go:build go1.18
     2  // +build go1.18
     3  
     4  package httpext
     5  
     6  import (
     7  	. "github.com/go-playground/assert/v2"
     8  	bytesext "github.com/go-playground/pkg/v5/bytes"
     9  	"net/http"
    10  	"net/http/httptest"
    11  	"testing"
    12  )
    13  
    14  func TestDecodeResponse(t *testing.T) {
    15  
    16  	type result struct {
    17  		ID int `json:"id" xml:"id"`
    18  	}
    19  
    20  	tests := []struct {
    21  		name     string
    22  		handler  http.HandlerFunc
    23  		expected result
    24  	}{
    25  		{
    26  			name: "Test JSON",
    27  			handler: func(w http.ResponseWriter, r *http.Request) {
    28  				Equal(t, JSON(w, http.StatusOK, result{ID: 3}), nil)
    29  			},
    30  			expected: result{ID: 3},
    31  		},
    32  		{
    33  			name: "Test XML",
    34  			handler: func(w http.ResponseWriter, r *http.Request) {
    35  				Equal(t, XML(w, http.StatusOK, result{ID: 5}), nil)
    36  			},
    37  			expected: result{ID: 5},
    38  		},
    39  	}
    40  
    41  	for _, tc := range tests {
    42  		tc := tc
    43  		t.Run(tc.name, func(t *testing.T) {
    44  			mux := http.NewServeMux()
    45  			mux.HandleFunc("/", tc.handler)
    46  
    47  			server := httptest.NewServer(mux)
    48  			defer server.Close()
    49  
    50  			req, err := http.NewRequest(http.MethodGet, server.URL, nil)
    51  			Equal(t, err, nil)
    52  
    53  			resp, err := http.DefaultClient.Do(req)
    54  			Equal(t, err, nil)
    55  			Equal(t, resp.StatusCode, http.StatusOK)
    56  
    57  			res, err := DecodeResponse[result](resp, bytesext.MiB)
    58  			Equal(t, err, nil)
    59  			Equal(t, tc.expected.ID, res.ID)
    60  		})
    61  	}
    62  }