MCPcopy Create free account
hub / github.com/cli/cli / NewMockHttpClient

Function NewMockHttpClient

internal/codespaces/connection/tunnels_api_server_mock.go:43–223  ·  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 ClientRelayURI: hostURL,
69 },
70 },
71 }
72
73 response, err = json.Marshal(*tunnel)
74 if err != nil {
75 log.Fatalf("json.Marshal returned an error: %v", err)
76 }
77
78 _, _ = w.Write(response)
79 return
80 } else if strings.HasPrefix(r.URL.Path, "/tunnels/tunnel-id/ports") {
81 // Use regex to capture the port number from the end of the path
82 re := regexp.MustCompile(`\/(\d+)$`)
83 matches := re.FindStringSubmatch(r.URL.Path)
84 targetingSpecificPort := len(matches) > 0
85
86 if targetingSpecificPort {
87 if r.Method == http.MethodDelete {
88 w.WriteHeader(http.StatusOK)
89 return
90 }
91
92 if r.Method == http.MethodGet {
93 // If no ports were configured, then we assume that every request for a port is valid.
94 if specifiedPorts == nil {
95 response, err := json.Marshal(tunnels.TunnelPort{
96 AccessControl: &tunnels.TunnelAccessControl{
97 Entries: []tunnels.TunnelAccessControlEntry{},
98 },
99 })
100

Callers 4

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 4

GetMockApiFunction · 0.74
TestNewPortForwarderFunction · 0.74