refactor: Modify implementation of TLS (#457)

* refactor: Don't generate certificates programmatically

* build: Add testdata folder to .dockerignore
This commit is contained in:
TwiN
2023-04-22 15:22:09 -04:00
committed by GitHub
parent 636688b43e
commit 83edca6e80
10 changed files with 109 additions and 143 deletions

View File

@ -10,7 +10,6 @@ import (
"github.com/TwiN/gatus/v5/config"
"github.com/TwiN/gatus/v5/config/web"
"github.com/TwiN/gatus/v5/core"
"github.com/TwiN/gatus/v5/test"
)
func TestHandle(t *testing.T) {
@ -46,38 +45,45 @@ func TestHandle(t *testing.T) {
}
}
func TestHandleTls(t *testing.T) {
privateKeyPath, publicKeyPath := test.UnsafeSelfSignedCertificates(t.TempDir())
cfg := &config.Config{
Web: &web.Config{
Address: "0.0.0.0",
Port: rand.Intn(65534),
Tls: (web.TLSConfig{CertificateFile: publicKeyPath, PrivateKeyFile: privateKeyPath}),
},
Endpoints: []*core.Endpoint{
{
Name: "frontend",
Group: "core",
},
{
Name: "backend",
Group: "core",
},
func TestHandleTLS(t *testing.T) {
scenarios := []struct {
name string
tls *web.TLSConfig
expectedStatusCode int
}{
{
name: "good-tls-config",
tls: &web.TLSConfig{CertificateFile: "../testdata/cert.pem", PrivateKeyFile: "../testdata/cert.key"},
expectedStatusCode: 200,
},
}
_ = os.Setenv("ROUTER_TEST", "true")
_ = os.Setenv("ENVIRONMENT", "dev")
defer os.Clearenv()
Handle(cfg)
defer Shutdown()
request, _ := http.NewRequest("GET", "/health", http.NoBody)
responseRecorder := httptest.NewRecorder()
server.Handler.ServeHTTP(responseRecorder, request)
if responseRecorder.Code != http.StatusOK {
t.Error("expected GET /health to return status code 200")
}
if server == nil {
t.Fatal("server should've been set (but because we set ROUTER_TEST, it shouldn't have been started)")
for _, scenario := range scenarios {
t.Run(scenario.name, func(t *testing.T) {
cfg := &config.Config{
Web: &web.Config{Address: "0.0.0.0", Port: rand.Intn(65534), TLS: scenario.tls},
Endpoints: []*core.Endpoint{
{Name: "frontend", Group: "core"},
{Name: "backend", Group: "core"},
},
}
if err := cfg.Web.ValidateAndSetDefaults(); err != nil {
t.Error("expected no error from web (TLS) validation, got", err)
}
_ = os.Setenv("ROUTER_TEST", "true")
_ = os.Setenv("ENVIRONMENT", "dev")
defer os.Clearenv()
Handle(cfg)
defer Shutdown()
request, _ := http.NewRequest("GET", "/health", http.NoBody)
responseRecorder := httptest.NewRecorder()
server.Handler.ServeHTTP(responseRecorder, request)
if responseRecorder.Code != scenario.expectedStatusCode {
t.Errorf("expected GET /health to return status code %d, got %d", scenario.expectedStatusCode, responseRecorder.Code)
}
if server == nil {
t.Fatal("server should've been set (but because we set ROUTER_TEST, it shouldn't have been started)")
}
})
}
}