wa-lang.org/wazero@v1.0.2/internal/gojs/http_test.go (about)

     1  package gojs_test
     2  
     3  import (
     4  	"errors"
     5  	"io"
     6  	"net/http"
     7  	"strings"
     8  	"testing"
     9  
    10  	"wa-lang.org/wazero"
    11  	gojs "wa-lang.org/wazero/imports/go"
    12  	"wa-lang.org/wazero/internal/testing/require"
    13  )
    14  
    15  type roundTripperFunc func(r *http.Request) (*http.Response, error)
    16  
    17  func (f roundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) {
    18  	return f(r)
    19  }
    20  
    21  func Test_http(t *testing.T) {
    22  	t.Parallel()
    23  
    24  	ctx := gojs.WithRoundTripper(testCtx, roundTripperFunc(func(req *http.Request) (*http.Response, error) {
    25  		if req.URL.Path == "/error" {
    26  			return nil, errors.New("error")
    27  		}
    28  		if req.Body != nil {
    29  			require.Equal(t, http.MethodPost, req.Method)
    30  			bytes, err := io.ReadAll(req.Body)
    31  			require.NoError(t, err)
    32  			require.Equal(t, "ice cream", string(bytes))
    33  		}
    34  		return &http.Response{
    35  			StatusCode:    http.StatusOK,
    36  			Status:        http.StatusText(http.StatusOK),
    37  			Header:        http.Header{"Custom": {"1"}},
    38  			Body:          io.NopCloser(strings.NewReader("abcdef")),
    39  			ContentLength: 6,
    40  		}, nil
    41  	}))
    42  
    43  	stdout, stderr, err := compileAndRun(ctx, "http", wazero.NewModuleConfig().
    44  		WithEnv("BASE_URL", "http://host"))
    45  
    46  	require.EqualError(t, err, `module "" closed with exit_code(0)`)
    47  	require.Zero(t, stderr)
    48  	require.Equal(t, `Get "http://host/error": net/http: fetch() failed: error
    49  1
    50  abcdef
    51  `, stdout)
    52  }