-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
317 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,204 @@ | ||
package main | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"log" | ||
"net/http" | ||
"net/http/httptest" | ||
"os" | ||
"sync" | ||
"syscall" | ||
"testing" | ||
"time" | ||
|
||
"zops.top/prometheus-cve-exporter/config" | ||
) | ||
|
||
func mockUpdateMetrics(*config.Config) {} | ||
|
||
func TestNewServer(t *testing.T) { | ||
cfg := &config.Config{} | ||
logger := log.New(os.Stdout, "", log.LstdFlags) | ||
server := NewServer(cfg, logger, mockUpdateMetrics) | ||
|
||
if server.cfg != cfg { | ||
t.Errorf("Expected cfg to be %v, got %v", cfg, server.cfg) | ||
} | ||
if server.logger != logger { | ||
t.Errorf("Expected logger to be %v, got %v", logger, server.logger) | ||
} | ||
if server.mux == nil { | ||
t.Error("Expected mux to be initialized") | ||
} | ||
if server.updateMetrics == nil { | ||
t.Error("Expected updateMetrics to be initialized") | ||
} | ||
} | ||
|
||
func TestSetupRouter(t *testing.T) { | ||
server := NewServer(&config.Config{}, log.New(os.Stdout, "", log.LstdFlags), mockUpdateMetrics) | ||
server.SetupRouter() | ||
|
||
testCases := []struct { | ||
path string | ||
expectedCode int | ||
}{ | ||
{"/metrics", http.StatusOK}, | ||
{"/", http.StatusOK}, | ||
{"/nonexistent", http.StatusNotFound}, | ||
} | ||
|
||
for _, tc := range testCases { | ||
req, err := http.NewRequest("GET", tc.path, nil) | ||
if err != nil { | ||
t.Fatalf("Could not create request: %v", err) | ||
} | ||
|
||
rr := httptest.NewRecorder() | ||
server.mux.ServeHTTP(rr, req) | ||
|
||
if rr.Code != tc.expectedCode { | ||
t.Errorf("handler returned wrong status code for %s: got %v want %v", | ||
tc.path, rr.Code, tc.expectedCode) | ||
} | ||
} | ||
} | ||
|
||
func TestHomeHandler(t *testing.T) { | ||
server := NewServer(&config.Config{}, log.New(os.Stdout, "", log.LstdFlags), mockUpdateMetrics) | ||
|
||
req, err := http.NewRequest("GET", "/", nil) | ||
if err != nil { | ||
t.Fatal(err) | ||
} | ||
|
||
rr := httptest.NewRecorder() | ||
handler := http.HandlerFunc(server.homeHandler) | ||
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) | ||
} | ||
|
||
expected := `<a href="/metrics">Go to metrics</a>` | ||
if rr.Body.String() != expected { | ||
t.Errorf("handler returned unexpected body: got %v want %v", | ||
rr.Body.String(), expected) | ||
} | ||
} | ||
|
||
func TestStart(t *testing.T) { | ||
cfg := &config.Config{Port: 20000} | ||
logger := log.New(os.Stdout, "", log.LstdFlags) | ||
server := NewServer(cfg, logger, mockUpdateMetrics) | ||
server.SetupRouter() | ||
|
||
var wg sync.WaitGroup | ||
wg.Add(1) | ||
go func() { | ||
defer wg.Done() | ||
server.Start() | ||
}() | ||
|
||
// Give some time for the server to start | ||
time.Sleep(100 * time.Millisecond) | ||
|
||
resp, err := http.Get(fmt.Sprintf("http://localhost:%d", cfg.Port)) | ||
if err != nil { | ||
t.Fatalf("Could not send GET request: %v", err) | ||
} | ||
defer resp.Body.Close() | ||
|
||
if resp.StatusCode != http.StatusOK { | ||
t.Errorf("Expected status OK; got %v", resp.Status) | ||
} | ||
|
||
// Shutdown the server | ||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | ||
defer cancel() | ||
server.server.Shutdown(ctx) | ||
Check failure on line 121 in cmd/prometheus-cve-exporter/main_test.go GitHub Actions / test
|
||
|
||
wg.Wait() | ||
} | ||
|
||
func TestUpdateMetricsExecution(t *testing.T) { | ||
updateMetricsCalled := false | ||
mockUpdateMetrics := func(*config.Config) { | ||
updateMetricsCalled = true | ||
} | ||
|
||
cfg := &config.Config{} | ||
logger := log.New(os.Stdout, "", log.LstdFlags) | ||
server := NewServer(cfg, logger, mockUpdateMetrics) | ||
|
||
server.updateMetrics(cfg) | ||
|
||
if !updateMetricsCalled { | ||
t.Error("Expected UpdateMetrics to be called") | ||
} | ||
} | ||
|
||
func TestMainIntegration(t *testing.T) { | ||
// Backup original os.Args | ||
oldArgs := os.Args | ||
defer func() { os.Args = oldArgs }() | ||
|
||
// Set up a test config file | ||
testConfigPath := "test_config.json" | ||
testPort := 20001 | ||
testConfigContent := []byte(fmt.Sprintf(`{ | ||
"nvd_feed_url": "https://test.nvd.feed.url", | ||
"update_interval": "2h", | ||
"port": %d, | ||
"severity": ["HIGH", "CRITICAL"], | ||
"package_file": "", | ||
"use_tls": false | ||
}`, testPort)) | ||
err := os.WriteFile(testConfigPath, testConfigContent, 0644) | ||
if err != nil { | ||
t.Fatalf("Failed to create test config file: %v", err) | ||
} | ||
defer os.Remove(testConfigPath) | ||
|
||
// Set the command-line argument to use our test config | ||
os.Args = []string{"cmd", "-config", testConfigPath} | ||
|
||
// Run main in a goroutine | ||
go func() { | ||
main() | ||
}() | ||
|
||
// Give some time for the server to start | ||
time.Sleep(100 * time.Millisecond) | ||
|
||
// Test if the server is running | ||
resp, err := http.Get(fmt.Sprintf("http://localhost:%d", testPort)) | ||
if err != nil { | ||
t.Fatalf("Could not send GET request: %v", err) | ||
} | ||
defer resp.Body.Close() | ||
|
||
if resp.StatusCode != http.StatusOK { | ||
t.Errorf("Expected status OK; got %v", resp.Status) | ||
} | ||
|
||
// Send shutdown signal | ||
syscall.Kill(syscall.Getpid(), syscall.SIGINT) | ||
Check failure on line 188 in cmd/prometheus-cve-exporter/main_test.go GitHub Actions / test
|
||
|
||
// Give some time for the server to shut down | ||
time.Sleep(500 * time.Millisecond) | ||
|
||
// Verify that the server has shut down | ||
_, err = http.Get(fmt.Sprintf("http://localhost:%d", testPort)) | ||
if err == nil { | ||
t.Error("Expected an error when connecting to a shutdown server") | ||
} | ||
} | ||
|
||
func TestMain(m *testing.M) { | ||
// Run tests | ||
code := m.Run() | ||
os.Exit(code) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters