github.com/fastly/cli@v1.7.2-0.20240304164155-9d0f1d77c3bf/pkg/mock/client.go (about) 1 package mock 2 3 import ( 4 "fmt" 5 "net/http" 6 7 "github.com/fastly/go-fastly/v9/fastly" 8 9 "github.com/fastly/cli/pkg/api" 10 ) 11 12 // APIClient takes a mock.API and returns an app.ClientFactory that uses that 13 // mock, ignoring the token and endpoint. It should only be used for tests. 14 func APIClient(a API) func(string, string, bool) (api.Interface, error) { 15 return func(token, endpoint string, debugMode bool) (api.Interface, error) { 16 fmt.Printf("token: %s\n", token) 17 fmt.Printf("endpoint: %s\n", endpoint) 18 fmt.Printf("debugMode: %t\n", debugMode) 19 return a, nil 20 } 21 } 22 23 // HTTPClient is used to mock fastly.Client requests. 24 type HTTPClient struct { 25 // Index keeps track of which Responses/Errors index to return. 26 Index int 27 // Responses tracks different responses to return. 28 Responses []*http.Response 29 // Errors tracks different errors to return. 30 Errors []error 31 } 32 33 // Get mocks a HTTP Client Get request. 34 func (c HTTPClient) Get(p string, _ *fastly.RequestOptions) (*http.Response, error) { 35 fmt.Printf("p: %#v\n", p) 36 // IMPORTANT: Have to increment on defer as index is already 0 by this point. 37 // This is opposite to the Do() method which is -1 at the time it's called. 38 defer func() { c.Index++ }() 39 return c.Responses[c.Index], c.Errors[c.Index] 40 } 41 42 // Do mocks a HTTP Client Do operation. 43 func (c HTTPClient) Do(r *http.Request) (*http.Response, error) { 44 fmt.Printf("r: %#v\n", r) 45 c.Index++ 46 return c.Responses[c.Index], c.Errors[c.Index] 47 } 48 49 // HTMLClient returns a mock HTTP Client that returns a stubbed response or 50 // error. 51 func HTMLClient(res []*http.Response, err []error) api.HTTPClient { 52 return HTTPClient{ 53 Index: -1, 54 Responses: res, 55 Errors: err, 56 } 57 }