This commit addresses several issues in the testing framework: - Corrected a malformed URL in the mock response data in `pkg/github/github.go`. - Fixed a bug in the mock HTTP client in `pkg/mocks/http.go` where the response body was being exhausted after the first read. The client now returns a deep copy of the response for each call. - Refactored the environment variable handling in `TDD/collect_commands_test.go` to use `t.Setenv`, ensuring proper cleanup after the test.
61 lines
1.7 KiB
Go
61 lines
1.7 KiB
Go
package mocks
|
|
|
|
import (
|
|
"bytes"
|
|
"io"
|
|
"net/http"
|
|
)
|
|
|
|
// MockRoundTripper is a mock implementation of http.RoundTripper.
|
|
type MockRoundTripper struct {
|
|
Responses map[string]*http.Response
|
|
}
|
|
|
|
// RoundTrip implements the http.RoundTripper interface.
|
|
func (m *MockRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
url := req.URL.String()
|
|
if resp, ok := m.Responses[url]; ok {
|
|
// Read the original body
|
|
bodyBytes, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
resp.Body.Close() // close original body
|
|
|
|
// Re-hydrate the original body so it can be read again
|
|
resp.Body = io.NopCloser(bytes.NewReader(bodyBytes))
|
|
|
|
// Create a deep copy of the response
|
|
newResp := &http.Response{
|
|
Status: resp.Status,
|
|
StatusCode: resp.StatusCode,
|
|
Proto: resp.Proto,
|
|
ProtoMajor: resp.ProtoMajor,
|
|
ProtoMinor: resp.ProtoMinor,
|
|
Header: resp.Header.Clone(),
|
|
Body: io.NopCloser(bytes.NewReader(bodyBytes)),
|
|
ContentLength: resp.ContentLength,
|
|
TransferEncoding: resp.TransferEncoding,
|
|
Close: resp.Close,
|
|
Uncompressed: resp.Uncompressed,
|
|
Trailer: resp.Trailer.Clone(),
|
|
Request: resp.Request,
|
|
TLS: resp.TLS,
|
|
}
|
|
return newResp, nil
|
|
}
|
|
return &http.Response{
|
|
StatusCode: http.StatusNotFound,
|
|
Body: io.NopCloser(bytes.NewBufferString("Not Found")),
|
|
Header: make(http.Header),
|
|
}, nil
|
|
}
|
|
|
|
// NewMockClient creates a new http.Client with a MockRoundTripper.
|
|
func NewMockClient(responses map[string]*http.Response) *http.Client {
|
|
return &http.Client{
|
|
Transport: &MockRoundTripper{
|
|
Responses: responses,
|
|
},
|
|
}
|
|
}
|