Iterate on new DownloadSchema testing

This commit is contained in:
Yann Hamon 2024-07-27 15:48:18 +02:00
parent ba26603549
commit 43596c9cfb

View file

@ -5,7 +5,6 @@ import (
"fmt" "fmt"
"math/rand" "math/rand"
"net/http" "net/http"
"os"
"testing" "testing"
"time" "time"
) )
@ -27,74 +26,70 @@ func (m *mockHTTPGetter) Get(url string) (resp *http.Response, err error) {
} }
func TestDownloadSchema(t *testing.T) { func TestDownloadSchema(t *testing.T) {
callCounts := map[string]int{}
firstAttempt := true
// http server to simulate different responses // http server to simulate different responses
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Check if the request is asking to simulate a connection reset or 503 var s int
// then return that status code once and then return a normal response callCounts[r.URL.Path]++
if r.URL.Path == "/simulate-reset" || r.URL.Path == "/503" { callCount := callCounts[r.URL.Path]
if firstAttempt {
firstAttempt = false switch r.URL.Path {
if r.URL.Path == "/simulate-reset" { case "/404":
if hj, ok := w.(http.Hijacker); ok { s = http.StatusNotFound
conn, _, err := hj.Hijack() case "/500":
if err != nil { s = http.StatusInternalServerError
fmt.Printf("Hijacking failed: %v\n", err) case "/503":
return if callCount < 2 {
} s = http.StatusServiceUnavailable
conn.Close() // Close the connection to simulate a reset
}
}
if r.URL.Path == "/503" {
w.WriteHeader(http.StatusServiceUnavailable)
w.Write([]byte("503 Service Unavailable"))
}
return
} else { } else {
firstAttempt = true s = http.StatusOK // Should succeed on 3rd try
w.WriteHeader(http.StatusOK) }
w.Write([]byte("Normal response"))
case "/simulate-reset":
if callCount < 2 {
if hj, ok := w.(http.Hijacker); ok {
conn, _, err := hj.Hijack()
if err != nil {
fmt.Printf("Hijacking failed: %v\n", err)
return
}
conn.Close() // Close the connection to simulate a reset
}
return return
} }
s = http.StatusOK // Should succeed on third try
default:
s = http.StatusOK
} }
if r.URL.Path == "/404" { w.WriteHeader(s)
w.WriteHeader(http.StatusNotFound) w.Write([]byte(http.StatusText(s)))
w.Write([]byte("404 Not Found"))
return
}
if r.URL.Path == "/500" {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 Internal Server Error"))
return
}
// Serve a normal response
w.WriteHeader(http.StatusOK)
w.Write([]byte("Normal response"))
}) })
port := fmt.Sprint(rand.Intn(1000) + 9000) // random port port := fmt.Sprint(rand.Intn(1000) + 9000) // random port
server := &http.Server{Addr: "127.0.0.1:" + port} server := &http.Server{Addr: "127.0.0.1:" + port}
url := fmt.Sprintf("http://localhost:%s", port)
go func() { go func() {
if err := server.ListenAndServe(); err != nil { if err := server.ListenAndServe(); err != nil {
fmt.Printf("Failed to start server: %v\n", err) fmt.Printf("Failed to start server: %v\n", err)
} }
}() }()
defer server.Shutdown(nil)
url := fmt.Sprintf("http://localhost:%s", port)
// Wait for the server to start // Wait for the server to start
for i := 0; i < 20; i++ { for i := 0; i < 20; i++ {
fmt.Printf("Trying to connect to server %d ...\n", i) if _, err := http.Get(url); err == nil {
_, err := http.Get(url)
if err == nil {
break break
} }
if i == 19 {
t.Error("http server did not start")
return
}
time.Sleep(50 * time.Millisecond) time.Sleep(50 * time.Millisecond)
} }
@ -113,7 +108,7 @@ func TestDownloadSchema(t *testing.T) {
"Deployment", "Deployment",
"v1", "v1",
"1.18.0", "1.18.0",
[]byte("Normal response"), []byte(http.StatusText(http.StatusOK)),
nil, nil,
}, },
{ {
@ -143,7 +138,7 @@ func TestDownloadSchema(t *testing.T) {
"Deployment", "Deployment",
"v1", "v1",
"1.18.0", "1.18.0",
[]byte("Normal response"), []byte(http.StatusText(http.StatusOK)),
nil, nil,
}, },
{ {
@ -153,19 +148,13 @@ func TestDownloadSchema(t *testing.T) {
"Deployment", "Deployment",
"v1", "v1",
"1.18.0", "1.18.0",
[]byte("Normal response"), []byte(http.StatusText(http.StatusOK)),
nil, nil,
}, },
} { } {
// create a temporary directory for the cache callCounts = map[string]int{} // Reinitialise counters
tmpDir, err := os.MkdirTemp("", "kubeconform-cache")
if err != nil {
t.Errorf("during test '%s': failed to create temp directory: %s", testCase.name, err)
continue
}
defer os.RemoveAll(tmpDir) // clean up the temporary directory
reg, err := newHTTPRegistry(testCase.schemaPathTemplate, tmpDir, testCase.strict, true, true) reg, err := newHTTPRegistry(testCase.schemaPathTemplate, "", testCase.strict, true, true)
if err != nil { if err != nil {
t.Errorf("during test '%s': failed to create registry: %s", testCase.name, err) t.Errorf("during test '%s': failed to create registry: %s", testCase.name, err)
continue continue