github.com/filecoin-project/bacalhau@v0.3.23-0.20230228154132-45c989550ace/pkg/compute/bidstrategy/external_http_strategy_test.go (about)

     1  //go:build unit || !integration
     2  
     3  package bidstrategy
     4  
     5  import (
     6  	"context"
     7  	"encoding/json"
     8  	"net/http"
     9  	"net/http/httptest"
    10  	"testing"
    11  
    12  	"github.com/stretchr/testify/require"
    13  )
    14  
    15  func TestJobSelectionHttp(t *testing.T) {
    16  	testCases := []struct {
    17  		name           string
    18  		failMode       bool
    19  		expectedResult bool
    20  	}{
    21  		{
    22  			"fail the response and don't select the job",
    23  			true,
    24  			false,
    25  		},
    26  		{
    27  			"succeed the response and select the job",
    28  			false,
    29  			true,
    30  		},
    31  	}
    32  
    33  	for _, test := range testCases {
    34  		t.Run(test.name, func(t *testing.T) {
    35  			var requestPayload JobSelectionPolicyProbeData
    36  
    37  			svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    38  				require.Equal(t, r.Method, "POST")
    39  				// Try to decode the request body into the struct. If there is an error,
    40  				// respond to the client with the error message and a 400 status code.
    41  				err := json.NewDecoder(r.Body).Decode(&requestPayload)
    42  				if err != nil {
    43  					http.Error(w, err.Error(), http.StatusBadRequest)
    44  					return
    45  				}
    46  
    47  				if test.failMode {
    48  					w.WriteHeader(http.StatusInternalServerError)
    49  					w.Write([]byte("500 - Something bad happened!"))
    50  				} else {
    51  					w.WriteHeader(http.StatusOK)
    52  					w.Write([]byte("200 - Everything is good!"))
    53  				}
    54  			}))
    55  			defer svr.Close()
    56  
    57  			params := ExternalHTTPStrategyParams{URL: svr.URL}
    58  			strategy := NewExternalHTTPStrategy(params)
    59  			request := getBidStrategyRequest()
    60  			result, err := strategy.ShouldBid(context.Background(), request)
    61  			require.NoError(t, err)
    62  			require.Equal(t, test.expectedResult, result.ShouldBid)
    63  
    64  			// this makes sure that the http payload was given to the http endpoint
    65  			require.Equal(t, request.Job.Metadata.ID, requestPayload.JobID)
    66  		})
    67  	}
    68  }