github.com/blend/go-sdk@v1.20220411.3/examples/r2/mock/main_test.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package main
     9  
    10  import (
    11  	"fmt"
    12  	"net/http"
    13  	"net/http/httptest"
    14  	"testing"
    15  	"time"
    16  
    17  	"github.com/blend/go-sdk/assert"
    18  	"github.com/blend/go-sdk/r2"
    19  )
    20  
    21  // RequestFactory creates a new request with a given set of options.
    22  type RequestFactory []r2.Option
    23  
    24  // New creates a new request.
    25  func (rf RequestFactory) New(target string, options ...r2.Option) *r2.Request {
    26  	return r2.New(target, append(rf, options...)...)
    27  }
    28  
    29  func (rf RequestFactory) Google() (*http.Response, error) {
    30  	return rf.New("https://google.com/robots.txt",
    31  		r2.OptUserAgent("blend go-sdk"),
    32  		r2.OptTimeout(5*time.Second),
    33  	).Discard()
    34  }
    35  
    36  func TestMockedRequest(t *testing.T) {
    37  	assert := assert.New(t)
    38  
    39  	var didCallHandler bool
    40  	mockServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
    41  		didCallHandler = true
    42  		rw.WriteHeader(200)
    43  		fmt.Fprint(rw, "OK!\n")
    44  	}))
    45  	defer mockServer.Close()
    46  
    47  	rf := RequestFactory([]r2.Option{r2.OptURL(mockServer.URL)})
    48  
    49  	res, err := rf.Google()
    50  	assert.Nil(err)
    51  	assert.Equal(http.StatusOK, res.StatusCode)
    52  	assert.True(didCallHandler)
    53  }