Skip to content

Commit 3334cc5

Browse files
LujeniSoulKyu
andauthored
ci(workflows): initial support for test (#14)
* ci(workflows): initial support for test Add a Makefile task to locally run it * test: create new tests for vault tasks using vault test server * build: add new dependancies for testing purpose * test: correct healthcheck test and prom test + Makefile issue --------- Co-authored-by: Guillaume LEGRAIN <[email protected]>
1 parent 2d3b69d commit 3334cc5

File tree

7 files changed

+2069
-192
lines changed

7 files changed

+2069
-192
lines changed

.github/workflows/test.yml

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# This workflow will build a golang project
2+
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-go
3+
4+
name: Go
5+
6+
on:
7+
push:
8+
branches: [ "main" ]
9+
pull_request:
10+
branches: [ "main" ]
11+
12+
jobs:
13+
14+
build:
15+
runs-on: ubuntu-latest
16+
steps:
17+
- uses: actions/checkout@v4
18+
19+
- name: Set up Go
20+
uses: actions/setup-go@v4
21+
with:
22+
go-version: '1.22'
23+
24+
- name: Build
25+
run: go build -v ./...
26+
27+
- name: Test
28+
run: go test -v ./...

Makefile

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,36 @@
22

33
VERSION ?= $(shell ./hack/get-version.sh)
44

5-
.PHONY:fmt vet build
5+
GO_IMG ?= golang:alpine3.20@sha256:1b455a3f7786e5765dbeb4f7ab32a36cdc0c3f4ddd35406606df612dc6e3269b
6+
7+
.PHONY: fmt vet build unit-test
8+
9+
DOCKER_CMD = docker run --rm -v $(PWD):/app -w /app ${GO_IMG}
10+
11+
## verify: Format code
612
fmt:
713
go fmt ./...
814

15+
## verify: Verify code
916
vet: fmt
1017
go vet ./...
1118

19+
## build: Build binary
1220
build: vet
1321
go build
1422

23+
## unit-test: Run unit tests
24+
unit-test:
25+
ifeq ($(USE_DOCKER), 1)
26+
@${DOCKER_CMD} go test -v ./...
27+
else
28+
go test -v ./... ;
29+
endif
30+
31+
## build-image: Build image
1532
build-docker: vet
1633
docker build -t numberly/vault-db-injector:${VERSION} .
1734

35+
## build-image: Push image
1836
push-docker: build-docker
1937
docker push numberly/vault-db-injector:${VERSION}

go.mod

Lines changed: 246 additions & 35 deletions
Large diffs are not rendered by default.

go.sum

Lines changed: 1441 additions & 105 deletions
Large diffs are not rendered by default.

pkg/healthcheck/healthceck_test.go renamed to pkg/healthcheck/healthcheck_test.go

Lines changed: 18 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,9 @@ package healthcheck
22

33
import (
44
"context"
5-
"io"
65
"net/http"
76
"net/http/httptest"
87
"strings"
9-
"sync/atomic"
108
"testing"
119
"time"
1210

@@ -32,11 +30,13 @@ func TestHealthzHandler(t *testing.T) {
3230
// logger.Initialize(yourConfigHere)
3331

3432
service := NewService()
35-
service.RegisterHandlers()
33+
34+
mux := http.NewServeMux()
35+
mux.HandleFunc("/healthz", service.healthzHandler)
3636

3737
req := httptest.NewRequest("GET", "/healthz", nil)
3838
w := httptest.NewRecorder()
39-
http.DefaultServeMux.ServeHTTP(w, req)
39+
mux.ServeHTTP(w, req)
4040

4141
if w.Code != http.StatusNoContent {
4242
t.Errorf("expected status %d, got %d", http.StatusNoContent, w.Code)
@@ -48,12 +48,15 @@ func TestReadyzHandler(t *testing.T) {
4848
// Assuming your logger has been initialized elsewhere or doing it here if needed
4949

5050
service := NewService()
51-
service.RegisterHandlers()
51+
52+
mux := http.NewServeMux()
53+
mux.HandleFunc("/readyz", service.readyzHandler())
54+
mux.HandleFunc("/healthz", service.healthzHandler)
5255

5356
// Test when the service is ready
5457
reqReady := httptest.NewRequest("GET", "/readyz", nil)
5558
wReady := httptest.NewRecorder()
56-
http.DefaultServeMux.ServeHTTP(wReady, reqReady)
59+
mux.ServeHTTP(wReady, reqReady)
5760

5861
if wReady.Code != http.StatusNoContent {
5962
t.Errorf("expected status %d when ready, got %d", http.StatusNoContent, wReady.Code)
@@ -63,58 +66,26 @@ func TestReadyzHandler(t *testing.T) {
6366
service.isReady.Store(false)
6467
reqNotReady := httptest.NewRequest("GET", "/readyz", nil)
6568
wNotReady := httptest.NewRecorder()
66-
http.DefaultServeMux.ServeHTTP(wNotReady, reqNotReady)
69+
mux.ServeHTTP(wNotReady, reqNotReady)
6770

6871
if wNotReady.Code != http.StatusServiceUnavailable {
6972
t.Errorf("expected status %d when not ready, got %d", http.StatusServiceUnavailable, wNotReady.Code)
7073
}
7174
}
7275

73-
// TestServiceStart remains largely the same as previously described.
74-
func TestServiceStart(t *testing.T) {
75-
ctx := context.TODO()
76-
// Assuming your logger has been initialized elsewhere or doing it here if needed
77-
initTestLogger()
78-
service := &Service{
79-
isReady: &atomic.Value{},
80-
server: &http.Server{
81-
Addr: "127.0.0.1:8888", // Use an ephemeral port
82-
ReadTimeout: 10 * time.Second,
83-
WriteTimeout: 10 * time.Second,
84-
},
85-
log: logger.GetLogger(), // Assuming logger has been initialized
86-
}
87-
service.isReady.Store(true)
88-
89-
service.RegisterHandlers()
90-
// Starting the service in a goroutine since it's blocking
91-
go func() {
92-
if err := service.Start(ctx, stopChan); err != nil {
93-
t.Errorf("failed to start service: %v", err)
94-
}
95-
}()
96-
97-
// Wait a short period to let the server start
98-
time.Sleep(1000 * time.Millisecond)
99-
100-
// Make a request to ensure the server is up and running
101-
resp, err := http.Get("http://" + service.server.Addr + "/healthz")
102-
if err != nil {
103-
t.Fatalf("failed to make request to the server: %v", err)
104-
}
105-
defer resp.Body.Close()
106-
107-
if resp.StatusCode != http.StatusNoContent {
108-
bodyBytes, _ := io.ReadAll(resp.Body)
109-
t.Errorf("expected status %d, got %d, body: %s", http.StatusNoContent, resp.StatusCode, string(bodyBytes))
110-
}
111-
}
112-
11376
func TestServiceShutdown(t *testing.T) {
11477
initTestLogger() // Ensure the logger is initialized if it's required for the test
11578

11679
// Create a new service and register handlers
11780
service := NewService()
81+
82+
mux := http.NewServeMux()
83+
service.server = &http.Server{
84+
Addr: "127.0.0.1:8888",
85+
Handler: mux,
86+
ReadTimeout: 10 * time.Second,
87+
WriteTimeout: 10 * time.Second,
88+
}
11889
service.RegisterHandlers()
11990

12091
// Create a cancelable context

pkg/prometheus/metrics_test.go

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ func TestRunMetrics(t *testing.T) {
3434
// Initialize the metric service
3535
service := prom.NewService(successChan)
3636

37-
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
37+
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
3838
defer cancel()
3939

4040
go service.RunMetrics()
@@ -46,13 +46,28 @@ func TestRunMetrics(t *testing.T) {
4646
t.Fatal("Test timed out waiting for RunMetrics to send success signal")
4747
}
4848

49-
serverURL := "http://" + "127.0.0.1:8080" + "/metrics"
50-
resp, err := http.Get(serverURL)
49+
serverURL := "http://127.0.0.1:8080/metrics"
50+
var resp *http.Response
51+
var err error
52+
53+
// Retry mechanism
54+
for i := 0; i < 5; i++ {
55+
resp, err = http.Get(serverURL)
56+
if err == nil {
57+
break
58+
}
59+
time.Sleep(500 * time.Millisecond)
60+
}
61+
5162
if err != nil {
5263
t.Fatalf("Failed to make a request to the server: %v", err)
5364
}
5465
defer resp.Body.Close()
5566

56-
bodyBytes, _ := io.ReadAll(resp.Body)
67+
bodyBytes, err := io.ReadAll(resp.Body)
68+
if err != nil {
69+
t.Fatalf("Failed to read response body: %v", err)
70+
}
71+
5772
assert.Equal(t, http.StatusOK, resp.StatusCode, "Expected status %d, got %d, body: %s", http.StatusOK, resp.StatusCode, string(bodyBytes))
5873
}

0 commit comments

Comments
 (0)