Skip to content

Commit

Permalink
Merge pull request #2512 from jhaals/jhaals/testmain
Browse files Browse the repository at this point in the history
Add more tests
  • Loading branch information
jhaals authored Oct 18, 2024
2 parents 7e239e1 + 51cca07 commit daf3785
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 3 deletions.
11 changes: 8 additions & 3 deletions cmd/yopass-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,7 @@ func main() {
if err != nil {
logger.Fatal("failed to setup database", zap.Error(err))
}
registry := prometheus.NewRegistry()
registry.MustRegister(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))
registry.MustRegister(collectors.NewGoCollector())
registry := setupRegistry()

cert := viper.GetString("tls-cert")
key := viper.GetString("tls-key")
Expand Down Expand Up @@ -120,6 +118,13 @@ func metricsHandler(r *prometheus.Registry) http.Handler {
return mx
}

func setupRegistry() *prometheus.Registry {
registry := prometheus.NewRegistry()
registry.MustRegister(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))
registry.MustRegister(collectors.NewGoCollector())
return registry
}

// configureZapLogger uses the `log-level` command line argument to set and replace the zap global logger.
func configureZapLogger() *zap.Logger {
loggerCfg := zap.NewProductionConfig()
Expand Down
41 changes: 41 additions & 0 deletions cmd/yopass-server/main_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package main

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/spf13/viper"
Expand Down Expand Up @@ -68,3 +70,42 @@ func TestSetupDatabaseInvalid(t *testing.T) {
t.Fatalf("Expected '%s', got '%v'", expected, err.Error())
}
}

func TestMetricsHandler(t *testing.T) {
registry := setupRegistry()

handler := metricsHandler(registry)

req, err := http.NewRequest("GET", "/metrics", nil)
if err != nil {
t.Fatalf("Could not create request: %v", err)
}

rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)

if status := rr.Code; status != http.StatusOK {
t.Errorf("Handler returned wrong status code: got %v want %v", status, http.StatusOK)
}

if body := rr.Body.String(); len(body) == 0 {
t.Error("Handler returned empty body")
}
}

func TestConfigureZapLogger(t *testing.T) {
logger := configureZapLogger()

if logger == nil {
t.Fatal("Expected non-nil logger")
}

// Check if logger is working by capturing logs
core, logs := observer.New(zapcore.DebugLevel)
testLogger := zap.New(core)
testLogger.Debug("test log message")

if logs.FilterMessage("test log message").Len() != 1 {
t.Error("Expected log message 'test log message'")
}
}

0 comments on commit daf3785

Please sign in to comment.