github.com/blend/go-sdk@v1.20220411.3/web/mock_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 web
     9  
    10  import (
    11  	"fmt"
    12  	"net/http"
    13  	"net/url"
    14  	"testing"
    15  
    16  	"github.com/blend/go-sdk/assert"
    17  	"github.com/blend/go-sdk/r2"
    18  	"github.com/blend/go-sdk/webutil"
    19  )
    20  
    21  func TestMock(t *testing.T) {
    22  	assert := assert.New(t)
    23  
    24  	app := MustNew()
    25  	app.GET("/", func(_ *Ctx) Result { return NoContent })
    26  
    27  	res, err := Mock(app, &http.Request{Method: "GET", URL: &url.URL{Scheme: webutil.SchemeHTTP, Path: "/"}}).Discard()
    28  	assert.Nil(err)
    29  	assert.Equal(http.StatusNoContent, res.StatusCode)
    30  
    31  	assert.True(app.IsStopped())
    32  
    33  	// try to make another request to the underlying test server
    34  
    35  	res, err = http.Get(res.Request.URL.String())
    36  	assert.NotNil(err)
    37  	assert.Nil(res)
    38  }
    39  
    40  func TestMockGet(t *testing.T) {
    41  	assert := assert.New(t)
    42  
    43  	app := MustNew()
    44  	app.GET("/", func(_ *Ctx) Result { return NoContent })
    45  
    46  	res, err := MockGet(app, "/").Discard()
    47  	assert.Nil(err)
    48  	assert.Equal(http.StatusNoContent, res.StatusCode)
    49  
    50  	assert.True(app.IsStopped())
    51  }
    52  
    53  func TestMockPostedFile(t *testing.T) {
    54  	assert := assert.New(t)
    55  
    56  	app := MustNew()
    57  	app.POST("/", func(r *Ctx) Result {
    58  		postedFiles, err := webutil.PostedFiles(r.Request)
    59  		if err != nil {
    60  			return Text.BadRequest(err)
    61  		}
    62  		if len(postedFiles) == 0 {
    63  			return Text.BadRequest(fmt.Errorf("there should be 2 files"))
    64  		}
    65  		return Text.OK()
    66  	})
    67  
    68  	res, err := MockMethod(app, http.MethodPost, "/",
    69  		r2.OptPostedFiles(
    70  			webutil.PostedFile{Key: "file0", FileName: "file0.txt", Contents: []byte("this is just a test")},
    71  			webutil.PostedFile{Key: "file1", FileName: "file1.txt", Contents: []byte("this is just a test")},
    72  		),
    73  	).Discard()
    74  	assert.Nil(err)
    75  	assert.Equal(http.StatusOK, res.StatusCode)
    76  }