From b39d1bf62fbcf46d04c6d2abfa8576cfb5f0daa6 Mon Sep 17 00:00:00 2001 From: Tobias Trabelsi Date: Fri, 20 Oct 2023 21:34:30 +0200 Subject: [PATCH] fix #2 and added some minimal tests --- .woodpecker.yml | 8 ++++++++ internal/config_test.go | 25 +++++++++++++++++++++++++ internal/health_test.go | 23 +++++++++++++++++++++++ internal/hetzner.go | 6 ++++++ 4 files changed, 62 insertions(+) create mode 100644 internal/config_test.go create mode 100644 internal/health_test.go diff --git a/.woodpecker.yml b/.woodpecker.yml index 71e4362..08f40ba 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -1,4 +1,12 @@ steps: + test: + image: golang + commands: + - go test ./... + when: + event: + - push + - pull_request build: image: woodpeckerci/plugin-docker-buildx settings: diff --git a/internal/config_test.go b/internal/config_test.go new file mode 100644 index 0000000..cbe4e97 --- /dev/null +++ b/internal/config_test.go @@ -0,0 +1,25 @@ +package internal + +import ( + "reflect" + "testing" +) + +var defaultConfig = Config{ + LogLevel: "Info", + LabelSelector: "kops.k8s.io/instance-role=Node", + Protocol: "http", + HcloudToken: "", + FloatingIPName: "", + DryRun: false, +} + +func TestConfigDefaults(t *testing.T) { + cfg, err := GenConfig() + if err != nil { + t.Errorf("%s", err.Error()) + } + if !reflect.DeepEqual(&defaultConfig, cfg) { + t.Errorf("got %+v, want %+v", cfg, defaultConfig) + } +} diff --git a/internal/health_test.go b/internal/health_test.go new file mode 100644 index 0000000..e7e8ed7 --- /dev/null +++ b/internal/health_test.go @@ -0,0 +1,23 @@ +package internal + +import ( + "net/http" + "strings" + "testing" +) + +func TestHealth(t *testing.T) { + go func() { + StartHealthEndpoint() + }() + request, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/health", strings.NewReader("")) + resp, err := http.DefaultClient.Do(request) + + if err != nil { + t.Errorf("Health endpoint did not start: %v", err) + } + + if resp.StatusCode != http.StatusOK { + t.Errorf("Bad response from health endpoint. Want: %d, got %d", http.StatusOK, resp.StatusCode) + } +} diff --git a/internal/hetzner.go b/internal/hetzner.go index 4c51c04..94121be 100644 --- a/internal/hetzner.go +++ b/internal/hetzner.go @@ -78,6 +78,12 @@ func AttachFloatingIpToNode(cfg *Config, server hcloud.Server) error { if err != nil { return errors.New(fmt.Sprintf("Could not find Floating IP by name: %s", err.Error())) } + if floatingIP.Server.ID == server.ID { + log.WithFields(log.Fields{ + "Caller": "AttachFloatingIpToNode", + }).Info(fmt.Sprintf("Floating IP %s already assigned to Node %s", cfg.FloatingIPName, server.Name)) + return nil + } _, _, err = client.FloatingIP.Assign(context.TODO(), floatingIP, &server) if err != nil { log.WithFields(log.Fields{