api_fake.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package api
  13. import (
  14. "encoding/json"
  15. "net/http"
  16. "net/http/httptest"
  17. )
  18. func newMockServer(status int, data any) *httptest.Server {
  19. body, err := json.Marshal(data)
  20. if err != nil {
  21. panic(err)
  22. }
  23. return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  24. w.WriteHeader(status)
  25. _, err := w.Write(body)
  26. if err != nil {
  27. panic(err)
  28. }
  29. }))
  30. }
  31. // NewMockClient creates an InfisicalClient with a mocked HTTP client that has a
  32. // fixed response.
  33. func NewMockClient(status int, data any) (*InfisicalClient, func()) {
  34. server := newMockServer(status, data)
  35. client, err := NewAPIClient(server.URL, server.Client())
  36. if err != nil {
  37. panic(err)
  38. }
  39. return client, server.Close
  40. }