github.com/google/osv-scalibr@v0.4.1/veles/secrets/github/mockgithub/mockgithub.go (about)

     1  // Copyright 2025 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package mockgithub contains a mock implementation of the Github APIss
    16  package mockgithub
    17  
    18  import (
    19  	"net/http"
    20  	"net/http/httptest"
    21  	"testing"
    22  )
    23  
    24  // Server creates a mock Github API server for testing
    25  func Server(t *testing.T, path string, code int, keys ...string) *httptest.Server {
    26  	t.Helper()
    27  
    28  	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    29  		// Check if it's a GET request to the expected endpoint.
    30  		if r.Method != http.MethodGet || r.URL.Path != path {
    31  			t.Errorf("unexpected request: %s %s, expected: GET %s", r.Method, r.URL.Path, path)
    32  			http.Error(w, "not found", http.StatusNotFound)
    33  			return
    34  		}
    35  
    36  		// If the user specified a hard-coded return code, like 500 just return it.
    37  		if code != http.StatusOK {
    38  			w.Header().Set("Content-Type", "application/json")
    39  			w.WriteHeader(code)
    40  			return
    41  		}
    42  
    43  		// Check if the Authorization header matches the expected key.
    44  		authHeader := r.Header.Get("Authorization")
    45  		for _, k := range keys {
    46  			if authHeader == "Bearer "+k {
    47  				w.Header().Set("Content-Type", "application/json")
    48  				w.WriteHeader(http.StatusOK)
    49  				return
    50  			}
    51  		}
    52  
    53  		w.Header().Set("Content-Type", "application/json")
    54  		w.WriteHeader(http.StatusUnauthorized)
    55  	}))
    56  }