MCPcopy
hub / github.com/cli/cli / NewMockHttpClient

Function NewMockHttpClient

internal/codespaces/connection/tunnels_api_server_mock.go:43–225  ·  view source on GitHub ↗
(opts ...mockClientOpt)

Source from the content-addressed store, hash-verified

41}
42
43func NewMockHttpClient(opts ...mockClientOpt) (*http.Client, error) {
44 mockClientOpts := &mockClientOpts{}
45 for _, opt := range opts {
46 opt(mockClientOpts)
47 }
48
49 specifiedPorts := mockClientOpts.ports
50
51 accessToken := "tunnel access-token"
52 relayServer, err := newMockrelayServer(withAccessToken(accessToken))
53 if err != nil {
54 return nil, fmt.Errorf("NewrelayServer returned an error: %w", err)
55 }
56
57 hostURL := strings.Replace(relayServer.URL(), "http://", "ws://", 1)
58 mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
59 var response []byte
60 if r.URL.Path == "/tunnels/tunnel-id" {
61 tunnel := &tunnels.Tunnel{
62 AccessTokens: map[tunnels.TunnelAccessScope]string{
63 tunnels.TunnelAccessScopeConnect: accessToken,
64 },
65 Endpoints: []tunnels.TunnelEndpoint{
66 {
67 HostID: "host1",
68 TunnelRelayTunnelEndpoint: tunnels.TunnelRelayTunnelEndpoint{
69 ClientRelayURI: hostURL,
70 },
71 },
72 },
73 }
74
75 response, err = json.Marshal(*tunnel)
76 if err != nil {
77 log.Fatalf("json.Marshal returned an error: %v", err)
78 }
79
80 _, _ = w.Write(response)
81 return
82 } else if strings.HasPrefix(r.URL.Path, "/tunnels/tunnel-id/ports") {
83 // Use regex to capture the port number from the end of the path
84 re := regexp.MustCompile(`\/(\d+)$`)
85 matches := re.FindStringSubmatch(r.URL.Path)
86 targetingSpecificPort := len(matches) > 0
87
88 if targetingSpecificPort {
89 if r.Method == http.MethodDelete {
90 w.WriteHeader(http.StatusOK)
91 return
92 }
93
94 if r.Method == http.MethodGet {
95 // If no ports were configured, then we assume that every request for a port is valid.
96 if specifiedPorts == nil {
97 response, err := json.Marshal(tunnels.TunnelPort{
98 AccessControl: &tunnels.TunnelAccessControl{
99 Entries: []tunnels.TunnelAccessControlEntry{},
100 },

Callers 3

GetMockApiFunction · 0.92
TestNewPortForwarderFunction · 0.92

Calls 6

newMockrelayServerFunction · 0.85
withAccessTokenFunction · 0.85
ReplaceMethod · 0.80
ErrorfMethod · 0.65
URLMethod · 0.65
WriteMethod · 0.65

Tested by 3

GetMockApiFunction · 0.74
TestNewPortForwarderFunction · 0.74