github.com/jenkins-x/jx/v2@v2.1.155/pkg/cmd/step/verify/step_verify_url_test.go (about)

     1  // +build unit
     2  
     3  package verify_test
     4  
     5  import (
     6  	"net/http"
     7  	"net/http/httptest"
     8  	"os"
     9  	"testing"
    10  	"time"
    11  
    12  	"github.com/jenkins-x/jx/v2/pkg/cmd/opts"
    13  	"github.com/jenkins-x/jx/v2/pkg/cmd/step/verify"
    14  	"github.com/stretchr/testify/assert"
    15  )
    16  
    17  func newTestServer(endpoint string, fn func(http.ResponseWriter, *http.Request)) *httptest.Server {
    18  	mux := http.NewServeMux()
    19  	mux.HandleFunc(endpoint, fn)
    20  	server := httptest.NewServer(mux)
    21  	return server
    22  }
    23  
    24  func TestStepVerifyURLSuccess(t *testing.T) {
    25  	t.Parallel()
    26  
    27  	endpoint := "/test"
    28  	server := newTestServer(endpoint, func(w http.ResponseWriter, r *http.Request) {
    29  		w.WriteHeader(http.StatusOK)
    30  	})
    31  	defer server.Close()
    32  
    33  	url := server.URL + endpoint
    34  	options := verify.StepVerifyURLOptions{
    35  		Endpoint: url,
    36  		Code:     http.StatusOK,
    37  		Timeout:  10 * time.Second,
    38  	}
    39  
    40  	commonOpts := opts.NewCommonOptionsWithFactory(nil)
    41  	commonOpts.Out = os.Stdout
    42  	commonOpts.Err = os.Stderr
    43  	options.CommonOptions = &commonOpts
    44  
    45  	err := options.Run()
    46  	assert.NoError(t, err, "should verify an endpoint which returns the expected code without error")
    47  }
    48  
    49  func TestStepVerifyURLFailure(t *testing.T) {
    50  	t.Parallel()
    51  
    52  	endpoint := "/test"
    53  	server := newTestServer(endpoint, func(w http.ResponseWriter, r *http.Request) {
    54  		w.WriteHeader(http.StatusInternalServerError)
    55  	})
    56  	defer server.Close()
    57  
    58  	url := server.URL + endpoint
    59  	options := verify.StepVerifyURLOptions{
    60  		Endpoint: url,
    61  		Code:     http.StatusOK,
    62  		Timeout:  5 * time.Second,
    63  	}
    64  
    65  	commonOpts := opts.NewCommonOptionsWithFactory(nil)
    66  	commonOpts.Out = os.Stdout
    67  	commonOpts.Err = os.Stderr
    68  	options.CommonOptions = &commonOpts
    69  
    70  	err := options.Run()
    71  	assert.Error(t, err, "should verify an endpoint which does not return the expected code with an error")
    72  }