From 68188d4348c8c9eaf08a7ff1b19325a3556b2e4c Mon Sep 17 00:00:00 2001 From: Joseph Kavanagh Date: Tue, 23 Apr 2024 14:32:57 +0100 Subject: [PATCH] test: deduplication (#392) --- .github/workflows/build-binary.yml | 2 +- cmd/argus/main_test.go | 32 +-- commands/announce_test.go | 29 +- commands/commands_test.go | 4 +- commands/help_test.go | 80 +----- commands/init_test.go | 24 +- commands/types_test.go | 23 +- config/defaults_test.go | 42 +-- config/help_test.go | 39 +-- config/settings_test.go | 73 ++--- db/help_test.go | 10 +- db/init_test.go | 2 +- notifiers/shoutrrr/gets_test.go | 215 +++++++-------- notifiers/shoutrrr/help_test.go | 37 +-- notifiers/shoutrrr/init_test.go | 5 +- notifiers/shoutrrr/shoutrrr_test.go | 31 +-- notifiers/shoutrrr/test/main.go | 15 +- notifiers/shoutrrr/test/main_test.go | 41 +-- notifiers/shoutrrr/verify_test.go | 208 +++++++-------- service/dashboard_test.go | 13 +- service/deployed_version/gets_test.go | 14 +- service/deployed_version/help_test.go | 15 +- service/deployed_version/init_test.go | 3 +- service/deployed_version/query_test.go | 6 +- service/deployed_version/refresh_test.go | 129 ++++----- service/deployed_version/types_test.go | 53 ++-- service/deployed_version/verify_test.go | 3 +- service/handlers_test.go | 252 +++++++++--------- service/help_test.go | 164 ++++-------- service/init_test.go | 9 +- service/latest_version/api_type/types_test.go | 5 +- service/latest_version/filter/command_test.go | 3 +- service/latest_version/filter/docker_test.go | 9 +- service/latest_version/filter/help_test.go | 10 +- service/latest_version/filter/require_test.go | 53 ++-- .../latest_version/filter/urlcommand_test.go | 61 ++--- service/latest_version/gets_test.go | 49 ++-- service/latest_version/help_test.go | 37 +-- service/latest_version/init_test.go | 3 +- service/latest_version/query_test.go | 34 +-- service/latest_version/refresh_test.go | 197 +++++++------- service/latest_version/types_test.go | 69 ++--- service/latest_version/verify_test.go | 13 +- service/new_test.go | 223 ++++++++-------- service/options/help_test.go | 9 +- service/options/options_test.go | 47 ++-- service/status/fails_test.go | 116 ++++---- service/status/help_test.go | 16 +- service/status/status_test.go | 65 ++--- service/track_test.go | 18 +- service/types_test.go | 193 +++++++------- test/main.go | 12 +- test/secrets.go | 31 +++ test/secrets_test.go | 56 ++++ testing/commands_test.go | 14 +- testing/help_test.go | 6 - testing/service_test.go | 34 +-- testing/shoutrrr_test.go | 42 +-- util/help_test.go | 5 - util/log_test.go | 6 +- util/regex_test.go | 10 +- util/template_test.go | 4 +- util/util_test.go | 62 ++--- web/api/types/argus_test.go | 191 ++++++------- web/api/types/help_test.go | 23 -- web/api/types/websocket_test.go | 12 +- web/api/v1/help_test.go | 35 --- web/api/v1/http-api-actions_test.go | 32 +-- web/api/v1/http-api-config_test.go | 2 +- web/api/v1/http-api-edit_test.go | 2 +- web/help_test.go | 101 ++----- web/web_test.go | 4 +- webhook/announce_test.go | 9 +- webhook/gets_test.go | 86 +++--- webhook/help_test.go | 66 +---- webhook/init_test.go | 11 +- webhook/send_test.go | 11 +- webhook/test/main.go | 81 ++++++ webhook/test/main_test.go | 241 +++++++++++++++++ webhook/types_test.go | 35 +-- webhook/verify_test.go | 20 +- 81 files changed, 2030 insertions(+), 2017 deletions(-) create mode 100644 test/secrets.go create mode 100644 test/secrets_test.go create mode 100644 webhook/test/main.go create mode 100644 webhook/test/main_test.go diff --git a/.github/workflows/build-binary.yml b/.github/workflows/build-binary.yml index 3a554d73..c288c835 100644 --- a/.github/workflows/build-binary.yml +++ b/.github/workflows/build-binary.yml @@ -34,7 +34,7 @@ jobs: - name: Use Node.js LTS uses: actions/setup-node@v4 with: - node-version: 20 + node-version: 20.x - name: Build web components run: make web diff --git a/cmd/argus/main_test.go b/cmd/argus/main_test.go index ac8f6a3b..b68494a6 100644 --- a/cmd/argus/main_test.go +++ b/cmd/argus/main_test.go @@ -27,22 +27,12 @@ import ( "github.com/release-argus/Argus/util" ) -func boolPtr(val bool) *bool { - return &val -} -func stringPtr(val string) *string { - return &val -} -func stringListPtr(val []string) *[]string { - return &val -} - func resetFlags() { - configFile = stringPtr("") - configCheckFlag = boolPtr(false) - testCommandsFlag = stringPtr("") - testNotifyFlag = stringPtr("") - testServiceFlag = stringPtr("") + configFile = test.StringPtr("") + configCheckFlag = test.BoolPtr(false) + testCommandsFlag = test.StringPtr("") + testNotifyFlag = test.StringPtr("") + testServiceFlag = test.StringPtr("") } func TestTheMain(t *testing.T) { @@ -57,21 +47,21 @@ func TestTheMain(t *testing.T) { "config with no services": { file: testYAML_NoServices, db: "test-no_services.db", - outputContains: stringListPtr([]string{ + outputContains: &[]string{ "Found 0 services to monitor", - "Listening on "})}, + "Listening on "}}, "config with services": { file: testYAML_Argus, db: "test-argus.db", - outputContains: stringListPtr([]string{ + outputContains: &[]string{ "services to monitor:", "release-argus/Argus, Latest Release - ", - "Listening on "})}, + "Listening on "}}, "config with services and some !active": { file: testYAML_Argus_SomeInactive, db: "test-argus-some-inactive.db", - outputContains: stringListPtr([]string{ - "Found 1 services to monitor:"})}, + outputContains: &[]string{ + "Found 1 services to monitor:"}}, } for name, tc := range tests { diff --git a/commands/announce_test.go b/commands/announce_test.go index 486f2228..99983c4d 100644 --- a/commands/announce_test.go +++ b/commands/announce_test.go @@ -22,6 +22,7 @@ import ( "time" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" api_type "github.com/release-argus/Argus/web/api/types" ) @@ -43,12 +44,12 @@ func TestController_AnnounceCommand(t *testing.T) { "failed does delay by 15s": { index: 0, timeDifference: 15 * time.Second, - failed: boolPtr(true), + failed: test.BoolPtr(true), }, "success does delay by 2*Interval": { index: 1, timeDifference: 22 * time.Minute, - failed: boolPtr(false), + failed: test.BoolPtr(false), }, } @@ -57,18 +58,18 @@ func TestController_AnnounceCommand(t *testing.T) { t.Parallel() controller := Controller{ - ParentInterval: stringPtr("11m"), + ParentInterval: test.StringPtr("11m"), ServiceStatus: &svcstatus.Status{ - ServiceID: stringPtr("some_service_id")}} + ServiceID: test.StringPtr("some_service_id")}} controller.Init( &svcstatus.Status{ - ServiceID: stringPtr("some_service_id")}, + ServiceID: test.StringPtr("some_service_id")}, &Slice{ {"ls", "-lah", "/root"}, {"ls", "-lah"}, {"ls", "-lah", "a"}}, nil, - stringPtr("11m")) + test.StringPtr("11m")) if !tc.nilChannel { announceChannel := make(chan []byte, 4) controller.ServiceStatus.AnnounceChannel = &announceChannel @@ -95,8 +96,8 @@ func TestController_AnnounceCommand(t *testing.T) { } // if they failed status matches - got := stringifyPointer(parsed.CommandData[(*controller.Command)[tc.index].String()].Failed) - want := stringifyPointer(controller.Failed.Get(tc.index)) + got := test.StringifyPtr(parsed.CommandData[(*controller.Command)[tc.index].String()].Failed) + want := test.StringifyPtr(controller.Failed.Get(tc.index)) if got != want { t.Errorf("want failed=%s\ngot failed=%s", want, got) @@ -124,13 +125,13 @@ func TestController_Find(t *testing.T) { }{ "command at first index": { command: "ls -lah", - want: intPtr(0)}, + want: test.IntPtr(0)}, "command at second index": { command: "ls -lah a", - want: intPtr(1)}, + want: test.IntPtr(1)}, "command with svcstatus": { command: "bash upgrade.sh 1.2.3", - want: intPtr(3)}, + want: test.IntPtr(3)}, "unknown command": { command: "ls -lah /root", want: nil}, @@ -151,7 +152,7 @@ func TestController_Find(t *testing.T) { Command{"bash", "upgrade.sh", "{{ version }}"}, }, ServiceStatus: &svcstatus.Status{ - ServiceID: stringPtr("some_service_id")}, + ServiceID: test.StringPtr("some_service_id")}, } controller.ServiceStatus.Init( 0, len(*controller.Command), 0, @@ -167,8 +168,8 @@ func TestController_Find(t *testing.T) { index := controller.Find(tc.command) // THEN the index is returned if it exists - got := stringifyPointer(index) - want := stringifyPointer(tc.want) + got := test.StringifyPtr(index) + want := test.StringifyPtr(tc.want) if got != want { t.Errorf("want: %s\ngot: %s", want, got) diff --git a/commands/commands_test.go b/commands/commands_test.go index 9416623d..d33e045f 100644 --- a/commands/commands_test.go +++ b/commands/commands_test.go @@ -120,14 +120,14 @@ func TestController_ExecIndex(t *testing.T) { svcStatus := svcstatus.New( &announce, nil, nil, "", "", "", "", "", "") - svcStatus.ServiceID = stringPtr("service_id") + svcStatus.ServiceID = test.StringPtr("service_id") controller.Init( svcStatus, &Slice{ {"date", "+%m-%d-%Y"}, {"false"}}, nil, - stringPtr("13m"), + test.StringPtr("13m"), ) tests := map[string]struct { index int diff --git a/commands/help_test.go b/commands/help_test.go index 0361f042..223cf79f 100644 --- a/commands/help_test.go +++ b/commands/help_test.go @@ -17,31 +17,24 @@ package command import ( - "fmt" "os" - "strings" "testing" - "github.com/release-argus/Argus/notifiers/shoutrrr" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) -func boolPtr(val bool) *bool { - return &val -} -func intPtr(val int) *int { - return &val -} -func stringPtr(val string) *string { - return &val -} -func stringifyPointer[T comparable](ptr *T) string { - str := "nil" - if ptr != nil { - str = fmt.Sprint(*ptr) - } - return str +func TestMain(m *testing.M) { + // initialize jLog + jLog = util.NewJLog("DEBUG", false) + jLog.Testing = true + + // run other tests + exitCode := m.Run() + + // exit + os.Exit(exitCode) } func testController(announce *chan []byte) (control *Controller) { @@ -49,60 +42,13 @@ func testController(announce *chan []byte) (control *Controller) { svcStatus := svcstatus.New( announce, nil, nil, "", "", "", "", "", "") - svcStatus.ServiceID = stringPtr("service_id") + svcStatus.ServiceID = test.StringPtr("service_id") control.Init( svcStatus, &Slice{{}, {}}, nil, - stringPtr("14m"), + test.StringPtr("14m"), ) return } - -func TestMain(m *testing.M) { - // initialize jLog - jLog = util.NewJLog("DEBUG", false) - jLog.Testing = true - - // run other tests - exitCode := m.Run() - - // exit - os.Exit(exitCode) -} - -func testShoutrrr(failing bool, selfSignedCert bool) *shoutrrr.Shoutrrr { - url := "valid.release-argus.io" - if selfSignedCert { - url = strings.Replace(url, "valid", "invalid", 1) - } - shoutrrr := shoutrrr.New( - nil, "", - &map[string]string{"max_tries": "1"}, - &map[string]string{}, - "gotify", - // trunk-ignore(gitleaks/generic-api-key) - &map[string]string{"host": url, "path": "/gotify", "token": "AGE-LlHU89Q56uQ"}, - shoutrrr.NewDefaults( - "", nil, nil, nil), - shoutrrr.NewDefaults( - "", nil, nil, nil), - shoutrrr.NewDefaults( - "", nil, nil, nil)) - shoutrrr.Main.InitMaps() - shoutrrr.Defaults.InitMaps() - shoutrrr.HardDefaults.InitMaps() - - shoutrrr.ID = "test" - shoutrrr.ServiceStatus = &svcstatus.Status{ - ServiceID: stringPtr("service"), - } - shoutrrr.ServiceStatus.Fails.Shoutrrr.Init(1) - shoutrrr.Failed = &shoutrrr.ServiceStatus.Fails.Shoutrrr - - if failing { - shoutrrr.URLFields["token"] = "invalid" - } - return shoutrrr -} diff --git a/commands/init_test.go b/commands/init_test.go index 3be989fd..7b15c2ff 100644 --- a/commands/init_test.go +++ b/commands/init_test.go @@ -22,7 +22,9 @@ import ( "github.com/prometheus/client_golang/prometheus/testutil" "github.com/release-argus/Argus/notifiers/shoutrrr" + test_shoutrrr "github.com/release-argus/Argus/notifiers/shoutrrr/test" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" metric "github.com/release-argus/Argus/web/metrics" ) @@ -30,12 +32,12 @@ func TestController_SetNextRunnable(t *testing.T) { // GIVEN a Controller with various Command's controller := Controller{} controller.Init( - &svcstatus.Status{ServiceID: stringPtr("service_id")}, + &svcstatus.Status{ServiceID: test.StringPtr("service_id")}, &Slice{ {"date", "+%m-%d-%Y"}, {"true"}, {"false"}, {"date", "+%m-%d-%Y"}, {"true"}, {"false"}}, nil, - stringPtr("11m")) + test.StringPtr("11m")) controller.Failed.Set(1, false) controller.Failed.Set(2, true) controller.Failed.Set(4, false) @@ -113,13 +115,13 @@ func TestController_IsRunnable(t *testing.T) { // GIVEN a Controller with various Command's controller := Controller{} controller.Init( - &svcstatus.Status{ServiceID: stringPtr("service_id")}, + &svcstatus.Status{ServiceID: test.StringPtr("service_id")}, &Slice{ {"date", "+%m-%d-%Y"}, {"true"}, {"false"}}, nil, - stringPtr("11m")) + test.StringPtr("11m")) controller.Failed.Set(1, false) controller.Failed.Set(2, true) nextRunnables := []time.Time{ @@ -164,13 +166,13 @@ func TestController_NextRunnable(t *testing.T) { // GIVEN a Controller with various Command's controller := Controller{} controller.Init( - &svcstatus.Status{ServiceID: stringPtr("service_id")}, + &svcstatus.Status{ServiceID: test.StringPtr("service_id")}, &Slice{ {"date", "+%m-%d-%Y"}, {"true"}, {"false"}}, nil, - stringPtr("11m")) + test.StringPtr("11m")) controller.Failed.Set(1, false) controller.Failed.Set(2, true) nextRunnables := []time.Time{ @@ -293,13 +295,13 @@ func TestController_Metrics(t *testing.T) { // GIVEN a Controller with multiple Command's controller := Controller{} controller.Init( - &svcstatus.Status{ServiceID: stringPtr("TestController_Metrics")}, + &svcstatus.Status{ServiceID: test.StringPtr("TestController_Metrics")}, &Slice{ {"date", "+%m-%d-%Y"}, {"true"}, {"false"}}, nil, - stringPtr("11m")) + test.StringPtr("11m")) controller.Failed.Set(1, false) controller.Failed.Set(2, true) nextRunnables := []time.Time{ @@ -376,14 +378,14 @@ func TestCommand_Init(t *testing.T) { command: &Slice{ {"date", "+%m-%d-%Y"}}, shoutrrrNotifiers: &shoutrrr.Slice{ - "test": testShoutrrr(false, false)}, + "test": test_shoutrrr.Shoutrrr(false, false)}, }, "nil parentInterval": { command: &Slice{ {"date", "+%m-%d-%Y"}}, }, "non-nil parentInterval": { - parentInterval: stringPtr("11m"), + parentInterval: test.StringPtr("11m"), command: &Slice{ {"date", "+%m-%d-%Y"}}}, } @@ -398,7 +400,7 @@ func TestCommand_Init(t *testing.T) { controller = &Controller{} } serviceStatus := svcstatus.Status{} - serviceStatus.ServiceID = stringPtr("TestInit") + serviceStatus.ServiceID = test.StringPtr("TestInit") controller.Init( &serviceStatus, tc.command, diff --git a/commands/types_test.go b/commands/types_test.go index 2ad2633a..9b2fc92f 100644 --- a/commands/types_test.go +++ b/commands/types_test.go @@ -21,6 +21,7 @@ import ( "time" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" ) func TestController_CopyFailsFrom(t *testing.T) { @@ -52,8 +53,8 @@ func TestController_CopyFailsFrom(t *testing.T) { from: &Controller{}, to: &Controller{}, fromFails: []*bool{ - boolPtr(true), - boolPtr(false), + test.BoolPtr(true), + test.BoolPtr(false), nil}, toFails: nil, }, @@ -65,7 +66,7 @@ func TestController_CopyFailsFrom(t *testing.T) { Command: &Slice{ {"ls", "-lah"}}}, fromFails: []*bool{ - boolPtr(true)}, + test.BoolPtr(true)}, toFails: []*bool{ nil}, fromNextRunnable: []time.Time{ @@ -79,9 +80,9 @@ func TestController_CopyFailsFrom(t *testing.T) { Command: &Slice{ {"ls", "-lah"}}}, fromFails: []*bool{ - boolPtr(true)}, + test.BoolPtr(true)}, toFails: []*bool{ - boolPtr(true)}, + test.BoolPtr(true)}, fromNextRunnable: []time.Time{ time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)}, toNextRunnable: []time.Time{ @@ -96,10 +97,10 @@ func TestController_CopyFailsFrom(t *testing.T) { Command: &Slice{ {"ls", "-lah"}}}, fromFails: []*bool{ - boolPtr(true), - boolPtr(false)}, + test.BoolPtr(true), + test.BoolPtr(false)}, toFails: []*bool{ - boolPtr(false)}, + test.BoolPtr(false)}, fromNextRunnable: []time.Time{ time.Date(2022, 2, 2, 0, 0, 0, 0, time.UTC), time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)}, @@ -151,11 +152,11 @@ func TestController_CopyFailsFrom(t *testing.T) { } // AND the matching fails are copied to the Controller for i := range tc.toFails { - if stringifyPointer(tc.toFails[i]) != stringifyPointer(tc.to.Failed.Get(i)) { + if test.StringifyPtr(tc.toFails[i]) != test.StringifyPtr(tc.to.Failed.Get(i)) { t.Errorf("Fail %d: expected %q, got %q", i, - stringifyPointer(tc.toFails[i]), - stringifyPointer(tc.to.Failed.Get(i))) + test.StringifyPtr(tc.toFails[i]), + test.StringifyPtr(tc.to.Failed.Get(i))) } } // AND the next_runnables are copied to the Controller diff --git a/config/defaults_test.go b/config/defaults_test.go index b428c19f..36078090 100644 --- a/config/defaults_test.go +++ b/config/defaults_test.go @@ -51,12 +51,12 @@ func TestDefaults_String(t *testing.T) { defaults: &Defaults{ Service: service.Defaults{ Options: *opt.NewDefaults( - "1m", // interval - boolPtr(false)), // semantic_versioning + "1m", // interval + test.BoolPtr(false)), // semantic_versioning LatestVersion: *latestver.NewDefaults( - stringPtr("foo"), // access_token - boolPtr(true), // allow_invalid_certs - boolPtr(false), // use_prerelease + test.StringPtr("foo"), // access_token + test.BoolPtr(true), // allow_invalid_certs + test.BoolPtr(false), // use_prerelease filter.NewRequireDefaults( filter.NewDockerCheckDefaults( "ghcr", // type @@ -71,9 +71,9 @@ func TestDefaults_String(t *testing.T) { nil))), ), DeployedVersionLookup: *deployedver.NewDefaults( - boolPtr(false)), // allow_invalid_certs + test.BoolPtr(false)), // allow_invalid_certs Dashboard: service.NewDashboardOptionsDefaults( - boolPtr(true))}, // auto_approve + test.BoolPtr(true))}, // auto_approve Notify: shoutrrr.SliceDefaults{ "discord": shoutrrr.NewDefaults( "", @@ -84,14 +84,14 @@ func TestDefaults_String(t *testing.T) { &map[string]string{ // url_params "host": "example.com"})}, WebHook: *webhook.NewDefaults( - boolPtr(true), // allow_invalid_certs + test.BoolPtr(true), // allow_invalid_certs &webhook.Headers{ // custom_headers {Key: "X-Header", Value: "foo"}}, "0s", // delay - intPtr(203), // desired_status_code - uintPtr(2), // max_tries + test.IntPtr(203), // desired_status_code + test.UIntPtr(2), // max_tries "secret!!!", // secret - boolPtr(false), // silent_fails + test.BoolPtr(false), // silent_fails "github", // type "https://example.comm"), // url }, @@ -226,7 +226,7 @@ func TestDefaults_MapEnvToStruct(t *testing.T) { "ARGUS_SERVICE_OPTIONS_SEMANTIC_VERSIONING": "true"}, want: &Defaults{ Service: service.Defaults{ - Options: *opt.NewDefaults("99m", boolPtr(true))}}, + Options: *opt.NewDefaults("99m", test.BoolPtr(true))}}, }, "service.options - invalid time.duration - interval": { env: map[string]string{ @@ -248,9 +248,9 @@ func TestDefaults_MapEnvToStruct(t *testing.T) { want: &Defaults{ Service: service.Defaults{ LatestVersion: *latestver.NewDefaults( - stringPtr("ghp_something"), - boolPtr(true), - boolPtr(true), + test.StringPtr("ghp_something"), + test.BoolPtr(true), + test.BoolPtr(true), nil)}}, }, "service.latest_version.require": { @@ -301,7 +301,7 @@ func TestDefaults_MapEnvToStruct(t *testing.T) { want: &Defaults{ Service: service.Defaults{ DeployedVersionLookup: *deployedver.NewDefaults( - boolPtr(true))}}, + test.BoolPtr(true))}}, }, "service.deployed_version - invalid bool - allow_invalid_certs": { env: map[string]string{ @@ -314,7 +314,7 @@ func TestDefaults_MapEnvToStruct(t *testing.T) { want: &Defaults{ Service: service.Defaults{ Dashboard: service.NewDashboardOptionsDefaults( - boolPtr(true))}}, + test.BoolPtr(true))}}, }, "service.dashboard - invalid bool - auto_approve": { env: map[string]string{ @@ -841,13 +841,13 @@ func TestDefaults_MapEnvToStruct(t *testing.T) { "ARGUS_WEBHOOK_URL": "webhook.example.com"}, want: &Defaults{ WebHook: *webhook.NewDefaults( - boolPtr(false), + test.BoolPtr(false), nil, "99s", - intPtr(201), - uintPtr(88), + test.IntPtr(201), + test.UIntPtr(88), "", - boolPtr(true), + test.BoolPtr(true), "github", "webhook.example.com")}, }, diff --git a/config/help_test.go b/config/help_test.go index 94c075a3..db3ce543 100644 --- a/config/help_test.go +++ b/config/help_test.go @@ -29,22 +29,16 @@ import ( "github.com/release-argus/Argus/service/latest_version/filter" opt "github.com/release-argus/Argus/service/options" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" "gopkg.in/yaml.v3" ) -func boolPtr(val bool) *bool { - return &val -} -func intPtr(val int) *int { - return &val -} -func stringPtr(val string) *string { - return &val -} -func uintPtr(val int) *uint { - converted := uint(val) - return &converted +func TestMain(m *testing.M) { + log := util.NewJLog("DEBUG", true) + log.Testing = true + LogInit(log) + os.Exit(m.Run()) } func testConfig() Config { @@ -111,8 +105,6 @@ func testLoad(file string, t *testing.T) (config *Config) { return } -var configInitMutex sync.Mutex - func testLoadBasic(file string, t *testing.T) (config *Config) { config = &Config{} @@ -156,7 +148,7 @@ func testServiceURL(id string) *service.Service { ID: id, LatestVersion: *latestver.New( nil, - boolPtr(false), + test.BoolPtr(false), nil, &opt.Options{}, &filter.Require{ @@ -166,24 +158,24 @@ func testServiceURL(id string) *service.Service { "url", "https://valid.release-argus.io/plain", &filter.URLCommandSlice{ - {Type: "regex", Regex: stringPtr("v([0-9.]+)")}}, - boolPtr(false), + {Type: "regex", Regex: test.StringPtr("v([0-9.]+)")}}, + test.BoolPtr(false), &latestver.LookupDefaults{}, &latestver.LookupDefaults{}), DeployedVersionLookup: deployedver.New( - boolPtr(false), + test.BoolPtr(false), nil, nil, "version", nil, "", nil, nil, "https://valid.release-argus.io/json", &deployedver.LookupDefaults{}, &deployedver.LookupDefaults{}), Dashboard: *service.NewDashboardOptions( - boolPtr(false), "test", "https://release-argus.io", "https://release-argus.io/docs", + test.BoolPtr(false), "test", "https://release-argus.io", "https://release-argus.io/docs", &service.DashboardOptionsDefaults{}, &service.DashboardOptionsDefaults{}), Status: *svcstatus.New( &announceChannel, &databaseChannel, &saveChannel, "", "", "", "", "", ""), Options: *opt.New( - boolPtr(true), "5s", boolPtr(true), + test.BoolPtr(true), "5s", test.BoolPtr(true), &opt.OptionsDefaults{}, &opt.OptionsDefaults{}), Defaults: &service.Defaults{}, HardDefaults: &service.Defaults{}} @@ -210,10 +202,3 @@ func testServiceURL(id string) *service.Service { svc.Status.SetDeployedVersionTimestamp("2001-01-01T01:01:01Z") return svc } - -func TestMain(m *testing.M) { - log := util.NewJLog("DEBUG", true) - log.Testing = true - LogInit(log) - os.Exit(m.Run()) -} diff --git a/config/settings_test.go b/config/settings_test.go index b4bbca4d..f04d3ef7 100644 --- a/config/settings_test.go +++ b/config/settings_test.go @@ -23,6 +23,7 @@ import ( "strings" "testing" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) @@ -67,81 +68,81 @@ func TestSettingsBase_CheckValues(t *testing.T) { had: Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - RoutePrefix: stringPtr("")}}}, + RoutePrefix: test.StringPtr("")}}}, want: Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - RoutePrefix: stringPtr("/")}}}, + RoutePrefix: test.StringPtr("/")}}}, }, "Route prefix - no leading /": { had: Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - RoutePrefix: stringPtr("test")}}}, + RoutePrefix: test.StringPtr("test")}}}, want: Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - RoutePrefix: stringPtr("/test")}}}, + RoutePrefix: test.StringPtr("/test")}}}, }, "Route prefix - leading /": { had: Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - RoutePrefix: stringPtr("/test")}}}, + RoutePrefix: test.StringPtr("/test")}}}, want: Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - RoutePrefix: stringPtr("/test")}}}, + RoutePrefix: test.StringPtr("/test")}}}, }, "Route prefix - multiple leading /": { had: Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - RoutePrefix: stringPtr("///test")}}}, + RoutePrefix: test.StringPtr("///test")}}}, want: Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - RoutePrefix: stringPtr("/test")}}}, + RoutePrefix: test.StringPtr("/test")}}}, }, "Route prefix - trailing /": { had: Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - RoutePrefix: stringPtr("/test/")}}}, + RoutePrefix: test.StringPtr("/test/")}}}, want: Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - RoutePrefix: stringPtr("/test")}}}, + RoutePrefix: test.StringPtr("/test")}}}, }, "Route prefix - multiple trailing /": { had: Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - RoutePrefix: stringPtr("/test///")}}}, + RoutePrefix: test.StringPtr("/test///")}}}, want: Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - RoutePrefix: stringPtr("/test")}}}, + RoutePrefix: test.StringPtr("/test")}}}, }, "Route prefix - only a /": { had: Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - RoutePrefix: stringPtr("/")}}}, + RoutePrefix: test.StringPtr("/")}}}, want: Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - RoutePrefix: stringPtr("/")}}}, + RoutePrefix: test.StringPtr("/")}}}, }, "Route prefix - only multiple /": { had: Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - RoutePrefix: stringPtr("///")}}}, + RoutePrefix: test.StringPtr("///")}}}, want: Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - RoutePrefix: stringPtr("/")}}}, + RoutePrefix: test.StringPtr("/")}}}, }, "Favicon - empty": { had: Settings{ @@ -221,12 +222,12 @@ func TestSettings_NilUndefinedFlags(t *testing.T) { }{ "flag set": { flagSet: true, - setStrTo: stringPtr("test"), - setBoolTo: boolPtr(true)}, + setStrTo: test.StringPtr("test"), + setBoolTo: test.BoolPtr(true)}, "flag not set": { flagSet: false, - setStrTo: stringPtr("foo"), - setBoolTo: boolPtr(false)}, + setStrTo: test.StringPtr("foo"), + setBoolTo: test.BoolPtr(false)}, } flagStr := "log.level" flagBool := "log.timestamps" @@ -288,7 +289,7 @@ func TestSettings_GetString(t *testing.T) { }, "log.level flag": { getFunc: settings.LogLevel, - flag: &LogLevel, flagVal: stringPtr("ERROR"), + flag: &LogLevel, flagVal: test.StringPtr("ERROR"), want: "ERROR", }, "data.database-file hard default": { @@ -302,7 +303,7 @@ func TestSettings_GetString(t *testing.T) { }, "data.database-file flag": { getFunc: settings.DataDatabaseFile, - flag: &DataDatabaseFile, flagVal: stringPtr("ERROR"), + flag: &DataDatabaseFile, flagVal: test.StringPtr("ERROR"), want: "ERROR", }, "web.listen-host hard default": { @@ -316,7 +317,7 @@ func TestSettings_GetString(t *testing.T) { }, "web.listen-host flag": { getFunc: settings.WebListenHost, - flag: &WebListenHost, flagVal: stringPtr("127.0.0.1"), + flag: &WebListenHost, flagVal: test.StringPtr("127.0.0.1"), want: "127.0.0.1", }, "web.listen-port hard default": { @@ -330,7 +331,7 @@ func TestSettings_GetString(t *testing.T) { }, "web.listen-port flag": { getFunc: settings.WebListenPort, - flag: &WebListenPort, flagVal: stringPtr("54321"), + flag: &WebListenPort, flagVal: test.StringPtr("54321"), want: "54321", }, "web.cert-file hard default": { @@ -344,7 +345,7 @@ func TestSettings_GetString(t *testing.T) { }, "web.cert-file flag": { getFuncPtr: settings.WebCertFile, - flag: &WebCertFile, flagVal: stringPtr("settings_test.go"), + flag: &WebCertFile, flagVal: test.StringPtr("settings_test.go"), want: "settings_test.go", }, "web.pkey-file hard default": { @@ -358,7 +359,7 @@ func TestSettings_GetString(t *testing.T) { }, "web.pkey-file flag": { getFuncPtr: settings.WebKeyFile, - flag: &WebPKeyFile, flagVal: stringPtr("settings_test.go"), + flag: &WebPKeyFile, flagVal: test.StringPtr("settings_test.go"), want: "settings_test.go", }, "web.route-prefix hard default": { @@ -372,7 +373,7 @@ func TestSettings_GetString(t *testing.T) { }, "web.route-prefix flag": { getFunc: settings.WebRoutePrefix, - flag: &WebRoutePrefix, flagVal: stringPtr("/flag"), + flag: &WebRoutePrefix, flagVal: test.StringPtr("/flag"), want: "/flag", }, "set from env": { @@ -381,7 +382,7 @@ func TestSettings_GetString(t *testing.T) { wantSettings: &Settings{ HardDefaults: SettingsBase{ Log: LogSettings{ - Level: stringPtr("ERROR")}}}, + Level: test.StringPtr("ERROR")}}}, }, } @@ -435,7 +436,7 @@ func TestSettings_MapEnvToStruct(t *testing.T) { want: &Settings{ SettingsBase: SettingsBase{ Log: LogSettings{ - Level: stringPtr("ERROR")}}}, + Level: test.StringPtr("ERROR")}}}, }, "log.timestamps": { env: map[string]string{ @@ -443,7 +444,7 @@ func TestSettings_MapEnvToStruct(t *testing.T) { want: &Settings{ SettingsBase: SettingsBase{ Log: LogSettings{ - Timestamps: boolPtr(true)}}}, + Timestamps: test.BoolPtr(true)}}}, }, "log.timestamps - invalid, not a bool": { env: map[string]string{ @@ -456,7 +457,7 @@ func TestSettings_MapEnvToStruct(t *testing.T) { want: &Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - ListenHost: stringPtr("test")}}}, + ListenHost: test.StringPtr("test")}}}, }, "web.listen-port": { env: map[string]string{ @@ -464,7 +465,7 @@ func TestSettings_MapEnvToStruct(t *testing.T) { want: &Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - ListenPort: stringPtr("123")}}}, + ListenPort: test.StringPtr("123")}}}, }, "web.cert-file": { env: map[string]string{ @@ -472,7 +473,7 @@ func TestSettings_MapEnvToStruct(t *testing.T) { want: &Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - CertFile: stringPtr("cert.test")}}}, + CertFile: test.StringPtr("cert.test")}}}, }, "web.pkey-file": { env: map[string]string{ @@ -480,7 +481,7 @@ func TestSettings_MapEnvToStruct(t *testing.T) { want: &Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - KeyFile: stringPtr("pkey.test")}}}, + KeyFile: test.StringPtr("pkey.test")}}}, }, "web.route-prefix": { env: map[string]string{ @@ -488,7 +489,7 @@ func TestSettings_MapEnvToStruct(t *testing.T) { want: &Settings{ SettingsBase: SettingsBase{ Web: WebSettings{ - RoutePrefix: stringPtr("/prefix")}}}, + RoutePrefix: test.StringPtr("/prefix")}}}, }, "web.basic_auth": { env: map[string]string{ @@ -572,7 +573,7 @@ func TestSettings_GetBool(t *testing.T) { want: "true"}, "log.timestamps flag": { getFuncPtr: settings.LogTimestamps, - flag: &LogTimestamps, flagVal: boolPtr(true), + flag: &LogTimestamps, flagVal: test.BoolPtr(true), want: "true"}, } diff --git a/db/help_test.go b/db/help_test.go index 8684fc48..828e2c96 100644 --- a/db/help_test.go +++ b/db/help_test.go @@ -28,6 +28,7 @@ import ( dbtype "github.com/release-argus/Argus/db/types" "github.com/release-argus/Argus/service" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) @@ -51,10 +52,6 @@ func TestMain(m *testing.M) { os.Exit(exitCode) } -func stringPtr(val string) *string { - return &val -} - func testConfig() (cfg *config.Config) { databaseFile := "test.db" databaseChannel := make(chan dbtype.Message, 16) @@ -97,7 +94,7 @@ func testConfig() (cfg *config.Config) { svc.Status.Init( len(svc.Notify), len(svc.Command), len(svc.WebHook), &svc.ID, - stringPtr("https://example.com")) + test.StringPtr("https://example.com")) svc.Status.SetApprovedVersion("1.0.0", false) svc.Status.SetDeployedVersion("2.0.0", false) svc.Status.SetDeployedVersionTimestamp(time.Now().Format(time.RFC3339)) @@ -119,6 +116,7 @@ func testAPI(primary string, secondary string) *api { return &testAPI } + func dbCleanup(api *api) { api.db.Close() os.Remove(*api.config.Settings.Data.DatabaseFile) @@ -169,7 +167,7 @@ func queryRow(t *testing.T, db *sql.DB, serviceID string) *svcstatus.Status { status.Init( 0, 0, 0, &id, - stringPtr("https://example.com")) + test.StringPtr("https://example.com")) status.SetLatestVersion(lv, false) status.SetLatestVersionTimestamp(lvt) status.SetDeployedVersion(dv, false) diff --git a/db/init_test.go b/db/init_test.go index 40ab3f5a..80ff7bb6 100644 --- a/db/init_test.go +++ b/db/init_test.go @@ -296,7 +296,7 @@ func TestAPI_Run(t *testing.T) { want.Init( 0, 0, 0, &target, - stringPtr("https://example.com")) + test.StringPtr("https://example.com")) want.SetLatestVersion("9.9.9", false) want.SetLatestVersionTimestamp("2022-01-01T01:01:01Z") want.SetApprovedVersion("0.0.1", false) diff --git a/notifiers/shoutrrr/gets_test.go b/notifiers/shoutrrr/gets_test.go index 3d80c544..1efe7d50 100644 --- a/notifiers/shoutrrr/gets_test.go +++ b/notifiers/shoutrrr/gets_test.go @@ -22,6 +22,7 @@ import ( "testing" "time" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) @@ -37,45 +38,45 @@ func TestShoutrrr_GetOption(t *testing.T) { }{ "root overrides all": { wantString: "this", - root: stringPtr("this"), - dfault: stringPtr("not_this"), - hardDefault: stringPtr("not_this"), + root: test.StringPtr("this"), + dfault: test.StringPtr("not_this"), + hardDefault: test.StringPtr("not_this"), }, "main overrides default and hardDefault": { wantString: "this", - main: stringPtr("this"), - dfault: stringPtr("not_this"), - hardDefault: stringPtr("not_this"), + main: test.StringPtr("this"), + dfault: test.StringPtr("not_this"), + hardDefault: test.StringPtr("not_this"), }, "default overrides hardDefault": { wantString: "this", - dfault: stringPtr("this"), - hardDefault: stringPtr("not_this"), + dfault: test.StringPtr("this"), + hardDefault: test.StringPtr("not_this"), }, "hardDefault is last resort": { wantString: "this", - hardDefault: stringPtr("this"), + hardDefault: test.StringPtr("this"), }, "env var is used": { wantString: "this", env: map[string]string{"TESTSHOUTRRR_GETOPTION_ONE": "this"}, - root: stringPtr("${TESTSHOUTRRR_GETOPTION_ONE}"), + root: test.StringPtr("${TESTSHOUTRRR_GETOPTION_ONE}"), }, "env var partial is used": { wantString: "this", env: map[string]string{"TESTSHOUTRRR_GETOPTION_TWO": "is"}, - root: stringPtr("th${TESTSHOUTRRR_GETOPTION_TWO}"), + root: test.StringPtr("th${TESTSHOUTRRR_GETOPTION_TWO}"), }, "empty env var is ignored": { wantString: "that", env: map[string]string{"TESTSHOUTRRR_GETOPTION_THREE": ""}, - root: stringPtr("${TESTSHOUTRRR_GETOPTION_THREE}"), - dfault: stringPtr("that"), + root: test.StringPtr("${TESTSHOUTRRR_GETOPTION_THREE}"), + dfault: test.StringPtr("that"), }, "undefined env var is used": { wantString: "${TESTSHOUTRRR_GETOPTION_UNSET}", - root: stringPtr("${TESTSHOUTRRR_GETOPTION_UNSET}"), - dfault: stringPtr("that"), + root: test.StringPtr("${TESTSHOUTRRR_GETOPTION_UNSET}"), + dfault: test.StringPtr("that"), }, } @@ -137,45 +138,45 @@ func TestShoutrrr_GetURLField(t *testing.T) { }{ "root overrides all": { wantString: "this", - root: stringPtr("this"), - dfault: stringPtr("not_this"), - hardDefault: stringPtr("not_this"), + root: test.StringPtr("this"), + dfault: test.StringPtr("not_this"), + hardDefault: test.StringPtr("not_this"), }, "main overrides default and hardDefault": { wantString: "this", - main: stringPtr("this"), - dfault: stringPtr("not_this"), - hardDefault: stringPtr("not_this"), + main: test.StringPtr("this"), + dfault: test.StringPtr("not_this"), + hardDefault: test.StringPtr("not_this"), }, "default overrides hardDefault": { wantString: "this", - dfault: stringPtr("this"), - hardDefault: stringPtr("not_this"), + dfault: test.StringPtr("this"), + hardDefault: test.StringPtr("not_this"), }, "hardDefault is last resort": { wantString: "this", - hardDefault: stringPtr("this"), + hardDefault: test.StringPtr("this"), }, "env var is used": { wantString: "this", env: map[string]string{"TESTSHOUTRRR_GETURLFIELD_ONE": "this"}, - root: stringPtr("${TESTSHOUTRRR_GETURLFIELD_ONE}"), + root: test.StringPtr("${TESTSHOUTRRR_GETURLFIELD_ONE}"), }, "env var partial is used": { wantString: "this", env: map[string]string{"TESTSHOUTRRR_GETURLFIELD_TWO": "is"}, - root: stringPtr("th${TESTSHOUTRRR_GETURLFIELD_TWO}"), + root: test.StringPtr("th${TESTSHOUTRRR_GETURLFIELD_TWO}"), }, "empty env var is ignored": { wantString: "that", env: map[string]string{"TESTSHOUTRRR_GETURLFIELD_THREE": ""}, - root: stringPtr("${TESTSHOUTRRR_GETURLFIELD_THREE}"), - dfault: stringPtr("that"), + root: test.StringPtr("${TESTSHOUTRRR_GETURLFIELD_THREE}"), + dfault: test.StringPtr("that"), }, "undefined env var is used": { wantString: "${TESTSHOUTRRR_GETURLFIELD_UNSET}", - root: stringPtr("${TESTSHOUTRRR_GETURLFIELD_UNSET}"), - dfault: stringPtr("that"), + root: test.StringPtr("${TESTSHOUTRRR_GETURLFIELD_UNSET}"), + dfault: test.StringPtr("that"), }, } @@ -237,45 +238,45 @@ func TestShoutrrr_GetParam(t *testing.T) { }{ "root overrides all": { wantString: "this", - root: stringPtr("this"), - dfault: stringPtr("not_this"), - hardDefault: stringPtr("not_this"), + root: test.StringPtr("this"), + dfault: test.StringPtr("not_this"), + hardDefault: test.StringPtr("not_this"), }, "main overrides default and hardDefault": { wantString: "this", - main: stringPtr("this"), - dfault: stringPtr("not_this"), - hardDefault: stringPtr("not_this"), + main: test.StringPtr("this"), + dfault: test.StringPtr("not_this"), + hardDefault: test.StringPtr("not_this"), }, "default overrides hardDefault": { wantString: "this", - dfault: stringPtr("this"), - hardDefault: stringPtr("not_this"), + dfault: test.StringPtr("this"), + hardDefault: test.StringPtr("not_this"), }, "hardDefault is last resort": { wantString: "this", - hardDefault: stringPtr("this"), + hardDefault: test.StringPtr("this"), }, "env var is used": { wantString: "this", env: map[string]string{"TESTSHOUTRRR_GETPARAM_ONE": "this"}, - root: stringPtr("${TESTSHOUTRRR_GETPARAM_ONE}"), + root: test.StringPtr("${TESTSHOUTRRR_GETPARAM_ONE}"), }, "env var partial is used": { wantString: "this", env: map[string]string{"TESTSHOUTRRR_GETPARAM_TWO": "is"}, - root: stringPtr("th${TESTSHOUTRRR_GETPARAM_TWO}"), + root: test.StringPtr("th${TESTSHOUTRRR_GETPARAM_TWO}"), }, "empty env var is ignored": { wantString: "that", env: map[string]string{"TESTSHOUTRRR_GETPARAM_THREE": ""}, - root: stringPtr("${TESTSHOUTRRR_GETPARAM_THREE}"), - dfault: stringPtr("that"), + root: test.StringPtr("${TESTSHOUTRRR_GETPARAM_THREE}"), + dfault: test.StringPtr("that"), }, "undefined env var is used": { wantString: "${TESTSHOUTRRR_GETPARAM_UNSET}", - root: stringPtr("${TESTSHOUTRRR_GETPARAM_UNSET}"), - dfault: stringPtr("that"), + root: test.StringPtr("${TESTSHOUTRRR_GETPARAM_UNSET}"), + dfault: test.StringPtr("that"), }, } @@ -336,25 +337,25 @@ func TestShoutrrr_GetDelay(t *testing.T) { }{ "root overrides all": { wantString: "1s", - root: stringPtr("1s"), - main: stringPtr("2s"), - dfault: stringPtr("2s"), - hardDefault: stringPtr("2s"), + root: test.StringPtr("1s"), + main: test.StringPtr("2s"), + dfault: test.StringPtr("2s"), + hardDefault: test.StringPtr("2s"), }, "main overrides default and hardDefault": { wantString: "1s", - main: stringPtr("1s"), - dfault: stringPtr("2s"), - hardDefault: stringPtr("2s"), + main: test.StringPtr("1s"), + dfault: test.StringPtr("2s"), + hardDefault: test.StringPtr("2s"), }, "default overrides hardDefault": { wantString: "1s", - dfault: stringPtr("1s"), - hardDefault: stringPtr("2s"), + dfault: test.StringPtr("1s"), + hardDefault: test.StringPtr("2s"), }, "hardDefault is last resort": { wantString: "1s", - hardDefault: stringPtr("1s"), + hardDefault: test.StringPtr("1s"), }, "no delay anywhere defaults to 0s": {wantString: "0s", root: nil, @@ -404,25 +405,25 @@ func TestShoutrrr_GetDelayDuration(t *testing.T) { }{ "root overrides all": { want: 1 * time.Second, - root: stringPtr("1s"), - main: stringPtr("2s"), - dfault: stringPtr("2s"), - hardDefault: stringPtr("2s"), + root: test.StringPtr("1s"), + main: test.StringPtr("2s"), + dfault: test.StringPtr("2s"), + hardDefault: test.StringPtr("2s"), }, "main overrides default and hardDefault": { want: 1 * time.Second, - main: stringPtr("1s"), - dfault: stringPtr("2s"), - hardDefault: stringPtr("2s"), + main: test.StringPtr("1s"), + dfault: test.StringPtr("2s"), + hardDefault: test.StringPtr("2s"), }, "default overrides hardDefault": { want: 1 * time.Second, - dfault: stringPtr("1s"), - hardDefault: stringPtr("2s"), + dfault: test.StringPtr("1s"), + hardDefault: test.StringPtr("2s"), }, "hardDefault is last resort": { want: 1 * time.Second, - hardDefault: stringPtr("1s"), + hardDefault: test.StringPtr("1s"), }, } @@ -468,25 +469,25 @@ func TestShoutrrr_GetMaxTries(t *testing.T) { }{ "root overrides all": { want: 1, - maxTriesRoot: stringPtr("1"), - maxTriesMain: stringPtr("2"), - maxTriesDefault: stringPtr("2"), - maxTriesHardDefault: stringPtr("2"), + maxTriesRoot: test.StringPtr("1"), + maxTriesMain: test.StringPtr("2"), + maxTriesDefault: test.StringPtr("2"), + maxTriesHardDefault: test.StringPtr("2"), }, "main overrides default and hardDefault": { want: 1, - maxTriesMain: stringPtr("1"), - maxTriesDefault: stringPtr("2"), - maxTriesHardDefault: stringPtr("2"), + maxTriesMain: test.StringPtr("1"), + maxTriesDefault: test.StringPtr("2"), + maxTriesHardDefault: test.StringPtr("2"), }, "default overrides hardDefault": { want: 1, - maxTriesDefault: stringPtr("1"), - maxTriesHardDefault: stringPtr("2"), + maxTriesDefault: test.StringPtr("1"), + maxTriesHardDefault: test.StringPtr("2"), }, "hardDefault is last resort": { want: 1, - maxTriesHardDefault: stringPtr("1"), + maxTriesHardDefault: test.StringPtr("1"), }, } @@ -538,38 +539,38 @@ func TestShoutrrr_Message(t *testing.T) { }{ "root overrides all": { want: "New version!", - root: stringPtr("New version!"), - main: stringPtr("something"), - dfault: stringPtr("something"), - hardDefault: stringPtr("something"), + root: test.StringPtr("New version!"), + main: test.StringPtr("something"), + dfault: test.StringPtr("something"), + hardDefault: test.StringPtr("something"), }, "main overrides default and hardDefault": { want: "New version!", - main: stringPtr("New version!"), - dfault: stringPtr("something"), - hardDefault: stringPtr("something"), + main: test.StringPtr("New version!"), + dfault: test.StringPtr("something"), + hardDefault: test.StringPtr("something"), }, "default overrides hardDefault": { want: "New version!", - dfault: stringPtr("New version!"), - hardDefault: stringPtr("something"), + dfault: test.StringPtr("New version!"), + hardDefault: test.StringPtr("something"), }, "hardDefault is last resort": { want: "New version!", - hardDefault: stringPtr("New version!"), + hardDefault: test.StringPtr("New version!"), }, "jinja templating": { want: "New version!", - root: stringPtr("{% if 'a' == 'a' %}New version!{% endif %}"), - dfault: stringPtr("something"), - hardDefault: stringPtr("something"), + root: test.StringPtr("{% if 'a' == 'a' %}New version!{% endif %}"), + dfault: test.StringPtr("something"), + hardDefault: test.StringPtr("something"), }, "jinja vars": { want: fmt.Sprintf("%s or %s/%s/releases/tag/%s", serviceInfo.WebURL, serviceInfo.URL, serviceInfo.ID, serviceInfo.LatestVersion), - root: stringPtr("{{ web_url }} or {{ service_url }}/{{ service_id }}/releases/tag/{{ version }}"), - dfault: stringPtr("something"), - hardDefault: stringPtr("something"), + root: test.StringPtr("{{ web_url }} or {{ service_url }}/{{ service_id }}/releases/tag/{{ version }}"), + dfault: test.StringPtr("something"), + hardDefault: test.StringPtr("something"), }, } @@ -621,38 +622,38 @@ func TestShoutrrr_Title(t *testing.T) { }{ "root overrides all": { want: "New version!", - root: stringPtr("New version!"), - main: stringPtr("something"), - dfault: stringPtr("something"), - hardDefault: stringPtr("something"), + root: test.StringPtr("New version!"), + main: test.StringPtr("something"), + dfault: test.StringPtr("something"), + hardDefault: test.StringPtr("something"), }, "main overrides default and hardDefault": { want: "New version!", - main: stringPtr("New version!"), - dfault: stringPtr("something"), - hardDefault: stringPtr("something"), + main: test.StringPtr("New version!"), + dfault: test.StringPtr("something"), + hardDefault: test.StringPtr("something"), }, "default overrides hardDefault": { want: "New version!", - dfault: stringPtr("New version!"), - hardDefault: stringPtr("something"), + dfault: test.StringPtr("New version!"), + hardDefault: test.StringPtr("something"), }, "hardDefault is last resort": { want: "New version!", - hardDefault: stringPtr("New version!"), + hardDefault: test.StringPtr("New version!"), }, "jinja templating": { want: "New version!", - root: stringPtr("{% if 'a' == 'a' %}New version!{% endif %}"), - dfault: stringPtr("something"), - hardDefault: stringPtr("something"), + root: test.StringPtr("{% if 'a' == 'a' %}New version!{% endif %}"), + dfault: test.StringPtr("something"), + hardDefault: test.StringPtr("something"), }, "jinja vars": { want: fmt.Sprintf("%s or %s/%s/releases/tag/%s", serviceInfo.WebURL, serviceInfo.URL, serviceInfo.ID, serviceInfo.LatestVersion), - root: stringPtr("{{ web_url }} or {{ service_url }}/{{ service_id }}/releases/tag/{{ version }}"), - dfault: stringPtr("something"), - hardDefault: stringPtr("something"), + root: test.StringPtr("{{ web_url }} or {{ service_url }}/{{ service_id }}/releases/tag/{{ version }}"), + dfault: test.StringPtr("something"), + hardDefault: test.StringPtr("something"), }, } diff --git a/notifiers/shoutrrr/help_test.go b/notifiers/shoutrrr/help_test.go index fa794ddb..00dcb56b 100644 --- a/notifiers/shoutrrr/help_test.go +++ b/notifiers/shoutrrr/help_test.go @@ -17,35 +17,15 @@ package shoutrrr import ( - "fmt" "os" "strings" "testing" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) -func boolPtr(val bool) *bool { - return &val -} -func intPtr(val int) *int { - return &val -} -func stringPtr(val string) *string { - return &val -} -func uintPtr(val int) *uint { - converted := uint(val) - return &converted -} -func stringifyPointer[T comparable](ptr *T) string { - str := "nil" - if ptr != nil { - str = fmt.Sprint(*ptr) - } - return str -} func TestMain(m *testing.M) { // initialize jLog jLog = util.NewJLog("DEBUG", false) @@ -69,7 +49,7 @@ func testShoutrrrDefaults(failing bool, selfSignedCert bool) *ShoutrrrDefaults { &map[string]string{"max_tries": "1"}, &map[string]string{}, // trunk-ignore(gitleaks/generic-api-key) - &map[string]string{"host": url, "path": "/gotify", "token": "AGE-LlHU89Q56uQ"}, + &map[string]string{"host": url, "path": "/gotify", "token": test.ShoutrrrGotifyToken()}, ) if failing { shoutrrr.URLFields["token"] = "invalid" @@ -87,8 +67,7 @@ func testShoutrrr(failing bool, selfSignedCert bool) *Shoutrrr { &map[string]string{"max_tries": "1"}, &map[string]string{}, "gotify", - // trunk-ignore(gitleaks/generic-api-key) - &map[string]string{"host": url, "path": "/gotify", "token": "AGE-LlHU89Q56uQ"}, + &map[string]string{"host": url, "path": "/gotify", "token": test.ShoutrrrGotifyToken()}, NewDefaults( "", nil, nil, nil), NewDefaults( @@ -101,7 +80,7 @@ func testShoutrrr(failing bool, selfSignedCert bool) *Shoutrrr { shoutrrr.ID = "test" shoutrrr.ServiceStatus = &svcstatus.Status{ - ServiceID: stringPtr("service"), + ServiceID: test.StringPtr("service"), } shoutrrr.ServiceStatus.Fails.Shoutrrr.Init(1) shoutrrr.Failed = &shoutrrr.ServiceStatus.Fails.Shoutrrr @@ -111,11 +90,3 @@ func testShoutrrr(failing bool, selfSignedCert bool) *Shoutrrr { } return shoutrrr } - -func trimJSON(str string) string { - str = strings.TrimSpace(str) - str = strings.ReplaceAll(str, "\n", "") - str = strings.ReplaceAll(str, "\t", "") - str = strings.ReplaceAll(str, ": ", ":") - return str -} diff --git a/notifiers/shoutrrr/init_test.go b/notifiers/shoutrrr/init_test.go index 75b4c15e..0e591d46 100644 --- a/notifiers/shoutrrr/init_test.go +++ b/notifiers/shoutrrr/init_test.go @@ -21,6 +21,7 @@ import ( "github.com/prometheus/client_golang/prometheus/testutil" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" metric "github.com/release-argus/Argus/web/metrics" ) @@ -50,7 +51,7 @@ func TestSlice_Metrics(t *testing.T) { if tc.slice != nil { for name, s := range *tc.slice { s.ID = name - s.ServiceStatus = &svcstatus.Status{ServiceID: stringPtr(name + "-service")} + s.ServiceStatus = &svcstatus.Status{ServiceID: test.StringPtr(name + "-service")} s.Main = &ShoutrrrDefaults{} s.Type = "gotify" } @@ -502,7 +503,7 @@ func TestSlice_Init(t *testing.T) { if tc.slice != nil { for i := range *tc.slice { if (*tc.slice)[i] != nil { - (*tc.slice)[i].ServiceStatus.ServiceID = stringPtr(name) + (*tc.slice)[i].ServiceStatus.ServiceID = test.StringPtr(name) (*tc.slice)[i].Options = tc.had } } diff --git a/notifiers/shoutrrr/shoutrrr_test.go b/notifiers/shoutrrr/shoutrrr_test.go index 9043e583..6e0bd4e3 100644 --- a/notifiers/shoutrrr/shoutrrr_test.go +++ b/notifiers/shoutrrr/shoutrrr_test.go @@ -20,6 +20,7 @@ import ( "fmt" "testing" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) @@ -541,36 +542,36 @@ func TestShoutrrr_BuildParams(t *testing.T) { }{ "root overrides all": { wantString: "this", - root: stringPtr("this"), - dfault: stringPtr("not_this"), - hardDefault: stringPtr("not_this"), + root: test.StringPtr("this"), + dfault: test.StringPtr("not_this"), + hardDefault: test.StringPtr("not_this"), }, "main overrides default and hardDefault": { wantString: "this", - main: stringPtr("this"), - dfault: stringPtr("not_this"), - hardDefault: stringPtr("not_this"), + main: test.StringPtr("this"), + dfault: test.StringPtr("not_this"), + hardDefault: test.StringPtr("not_this"), }, "default overrides hardDefault": { wantString: "this", - dfault: stringPtr("this"), - hardDefault: stringPtr("not_this"), + dfault: test.StringPtr("this"), + hardDefault: test.StringPtr("not_this"), }, "hardDefault is last resort": { wantString: "this", - hardDefault: stringPtr("this"), + hardDefault: test.StringPtr("this"), }, "jinja templating": { wantString: "this", - root: stringPtr("{% if 'a' == 'a' %}this{% endif %}"), - dfault: stringPtr("not_this"), - hardDefault: stringPtr("not_this"), + root: test.StringPtr("{% if 'a' == 'a' %}this{% endif %}"), + dfault: test.StringPtr("not_this"), + hardDefault: test.StringPtr("not_this"), }, "jinja vars": { wantString: fmt.Sprintf("foo%s-%s", serviceInfo.ID, serviceInfo.LatestVersion), - root: stringPtr("foo{{ service_id }}-{{ version }}"), - dfault: stringPtr("not_this"), - hardDefault: stringPtr("not_this"), + root: test.StringPtr("foo{{ service_id }}-{{ version }}"), + dfault: test.StringPtr("not_this"), + hardDefault: test.StringPtr("not_this"), }, } diff --git a/notifiers/shoutrrr/test/main.go b/notifiers/shoutrrr/test/main.go index 737c9021..48f74780 100644 --- a/notifiers/shoutrrr/test/main.go +++ b/notifiers/shoutrrr/test/main.go @@ -17,7 +17,6 @@ package test import ( - "os" "strings" "github.com/release-argus/Argus/notifiers/shoutrrr" @@ -25,16 +24,6 @@ import ( "github.com/release-argus/Argus/test" ) -// testShoutrrrrGotifyToken returns the token for the Gotify test -func testShoutrrrrGotifyToken() (token string) { - token = os.Getenv("ARGUS_TEST_GOTIFY_TOKEN") - if token == "" { - // trunk-ignore(gitleaks/generic-api-key) - token = "AGE-LlHU89Q56uQ" - } - return -} - // ShoutrrrDefaults returns a ShoutrrrDefaults instance for testing func ShoutrrrDefaults(failing bool, selfSignedCert bool) *shoutrrr.ShoutrrrDefaults { url := "valid.release-argus.io" @@ -48,7 +37,7 @@ func ShoutrrrDefaults(failing bool, selfSignedCert bool) *shoutrrr.ShoutrrrDefau &map[string]string{ "host": url, "path": "/gotify", - "token": testShoutrrrrGotifyToken()}, + "token": test.ShoutrrrGotifyToken()}, ) if failing { shoutrrr.URLFields["token"] = "invalid" @@ -70,7 +59,7 @@ func Shoutrrr(failing bool, selfSignedCert bool) *shoutrrr.Shoutrrr { &map[string]string{ "host": url, "path": "/gotify", - "token": testShoutrrrrGotifyToken()}, + "token": test.ShoutrrrGotifyToken()}, shoutrrr.NewDefaults( "", nil, nil, nil), shoutrrr.NewDefaults( diff --git a/notifiers/shoutrrr/test/main_test.go b/notifiers/shoutrrr/test/main_test.go index 129fef19..85fc23c3 100644 --- a/notifiers/shoutrrr/test/main_test.go +++ b/notifiers/shoutrrr/test/main_test.go @@ -12,46 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -//go:build unit +//go:build unit || integration package test import ( - "os" "testing" -) - -func TestShoutrrrrGotifyToken(t *testing.T) { - // GIVEN the environment variable ARGUS_TEST_GOTIFY_TOKEN - tests := map[string]struct { - env string - }{ - "empty": {env: ""}, - "set": {env: "test"}, - } - - for name, tc := range tests { - t.Run(name, func(t *testing.T) { - // t.Parallel() - not parallel because we are manipulating the environment - - want := "AGE-LlHU89Q56uQ" - if tc.env != "" { - os.Setenv("ARGUS_TEST_GOTIFY_TOKEN", tc.env) - defer os.Unsetenv("ARGUS_TEST_GOTIFY_TOKEN") - want = tc.env - } - - // WHEN testShoutrrrrGotifyToken is called - token := testShoutrrrrGotifyToken() - // THEN the token should be as expected - if token != want { - t.Errorf("expected %q but got %q", - want, token) - } - }) - } -} + "github.com/release-argus/Argus/test" +) func TestShoutrrrDefaults(t *testing.T) { // GIVEN the failing and self-signed certificate flags @@ -69,7 +38,7 @@ func TestShoutrrrDefaults(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - wantToken := "AGE-LlHU89Q56uQ" + wantToken := test.ShoutrrrGotifyToken() if tc.failing { wantToken = "invalid" } @@ -111,7 +80,7 @@ func TestShoutrrr(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - wantToken := "AGE-LlHU89Q56uQ" + wantToken := test.ShoutrrrGotifyToken() if tc.failing { wantToken = "invalid" } diff --git a/notifiers/shoutrrr/verify_test.go b/notifiers/shoutrrr/verify_test.go index 53b8792d..4ed442a0 100644 --- a/notifiers/shoutrrr/verify_test.go +++ b/notifiers/shoutrrr/verify_test.go @@ -40,64 +40,64 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { }{ "no type": { errsRegex: "type: ", - sType: stringPtr(""), + sType: test.StringPtr(""), }, "invalid type": { errsRegex: "type: .* ", - sType: stringPtr("argus"), + sType: test.StringPtr("argus"), }, "invalid type - type in main differs": { errsRegex: `type: "gotify" != "discord" `, errsURLFieldsRegex: `host: .*token: `, - sType: stringPtr("gotify"), + sType: test.StringPtr("gotify"), main: NewDefaults("discord", nil, nil, nil), }, "bark - invalid": { - sType: stringPtr("bark"), + sType: test.StringPtr("bark"), errsURLFieldsRegex: `^ devicekey: [^:]+host: [^:]+$`, }, "bark - no devicekey": { - sType: stringPtr("bark"), + sType: test.StringPtr("bark"), errsURLFieldsRegex: `^ devicekey: [^:]+$`, urlFields: map[string]string{ "host": "https://example.com"}, }, "bark - no host": { - sType: stringPtr("bark"), + sType: test.StringPtr("bark"), errsURLFieldsRegex: `^ host: [^:]+$`, urlFields: map[string]string{ "devicekey": "foo"}, }, "bark - valid": { - sType: stringPtr("bark"), + sType: test.StringPtr("bark"), urlFields: map[string]string{ "devicekey": "foo", "host": "https://example.com"}, }, "discord - invalid": { - sType: stringPtr("discord"), + sType: test.StringPtr("discord"), errsURLFieldsRegex: "token: .*webhookid: ", }, "discord - no token": { - sType: stringPtr("discord"), + sType: test.StringPtr("discord"), errsURLFieldsRegex: "token: ", urlFields: map[string]string{ "webhookid": "bash"}, }, "discord - no webhookid": { - sType: stringPtr("discord"), + sType: test.StringPtr("discord"), errsURLFieldsRegex: "webhookid: ", urlFields: map[string]string{ "token": "bish"}, }, "discord - valid": { - sType: stringPtr("discord"), + sType: test.StringPtr("discord"), urlFields: map[string]string{ "token": "bish", "webhookid": "webhookid"}, }, "discord - valid with main": { - sType: stringPtr("discord"), + sType: test.StringPtr("discord"), main: NewDefaults( "", nil, nil, &map[string]string{ @@ -105,19 +105,19 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "webhookid": "bash"}), }, "smtp - invalid": { - sType: stringPtr("smtp"), + sType: test.StringPtr("smtp"), errsURLFieldsRegex: "host: .*", errsParamsRegex: "fromaddress: .*toaddresses: ", }, "smtp - no host": { - sType: stringPtr("smtp"), + sType: test.StringPtr("smtp"), errsURLFieldsRegex: "host: ", params: map[string]string{ "fromaddress": "bash", "toaddresses": "bosh"}, }, "smtp - no fromaddress": { - sType: stringPtr("smtp"), + sType: test.StringPtr("smtp"), errsParamsRegex: "fromaddress: ", urlFields: map[string]string{ "host": "bish"}, @@ -125,7 +125,7 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "toaddresses": "bosh"}, }, "smtp - no toaddresses": { - sType: stringPtr("smtp"), + sType: test.StringPtr("smtp"), errsParamsRegex: "toaddresses: ", urlFields: map[string]string{ "host": "bish"}, @@ -133,7 +133,7 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "fromaddress": "bash"}, }, "smtp - valid": { - sType: stringPtr("smtp"), + sType: test.StringPtr("smtp"), urlFields: map[string]string{ "host": "bish"}, params: map[string]string{ @@ -141,7 +141,7 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "toaddresses": "bosh"}, }, "smtp - valid with main": { - sType: stringPtr("smtp"), + sType: test.StringPtr("smtp"), main: NewDefaults( "", nil, &map[string]string{ @@ -151,29 +151,29 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "host": "bish"}), }, "gotify - invalid": { - sType: stringPtr("gotify"), + sType: test.StringPtr("gotify"), errsURLFieldsRegex: "host: .*token: ", }, "gotify - no host": { - sType: stringPtr("gotify"), + sType: test.StringPtr("gotify"), errsURLFieldsRegex: "host: ", urlFields: map[string]string{ "token": "bash"}, }, "gotify - no token": { - sType: stringPtr("gotify"), + sType: test.StringPtr("gotify"), errsURLFieldsRegex: "token: ", urlFields: map[string]string{ "host": "bish"}, }, "gotify - valid": { - sType: stringPtr("gotify"), + sType: test.StringPtr("gotify"), urlFields: map[string]string{ "host": "bish", "token": "bash"}, }, "gotify - valid with main": { - sType: stringPtr("gotify"), + sType: test.StringPtr("gotify"), main: NewDefaults( "", nil, nil, &map[string]string{ @@ -181,47 +181,47 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "token": "bash"}), }, "googlechat - invalid": { - sType: stringPtr("googlechat"), + sType: test.StringPtr("googlechat"), errsURLFieldsRegex: "raw: ", }, "googlechat - valid": { - sType: stringPtr("googlechat"), + sType: test.StringPtr("googlechat"), urlFields: map[string]string{ "raw": "bish"}, }, "googlechat - valid with main": { - sType: stringPtr("googlechat"), + sType: test.StringPtr("googlechat"), main: NewDefaults( "", nil, nil, &map[string]string{ "raw": "bish"}), }, "ifttt - invalid": { - sType: stringPtr("ifttt"), + sType: test.StringPtr("ifttt"), errsURLFieldsRegex: "webhookid: ", errsParamsRegex: "events: ", }, "ifttt - no webhookid": { - sType: stringPtr("ifttt"), + sType: test.StringPtr("ifttt"), errsURLFieldsRegex: "webhookid: ", urlFields: map[string]string{}, params: map[string]string{ "events": "bash"}, }, "ifttt - no events": { - sType: stringPtr("ifttt"), + sType: test.StringPtr("ifttt"), errsParamsRegex: "events: ", urlFields: map[string]string{ "webhookid": "bish"}, }, "ifttt - valid": { - sType: stringPtr("ifttt"), + sType: test.StringPtr("ifttt"), urlFields: map[string]string{ "webhookid": "bish"}, params: map[string]string{ "events": "events"}, }, "ifttt - valid with main": { - sType: stringPtr("ifttt"), + sType: test.StringPtr("ifttt"), main: NewDefaults( "", nil, &map[string]string{ @@ -230,31 +230,31 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "webhookid": "webhookid"}), }, "join - invalid": { - sType: stringPtr("join"), + sType: test.StringPtr("join"), errsURLFieldsRegex: "apikey: ", errsParamsRegex: "devices: ", }, "join - no apikey": { - sType: stringPtr("join"), + sType: test.StringPtr("join"), errsURLFieldsRegex: "apikey: ", urlFields: map[string]string{}, params: map[string]string{ "devices": "bash"}, }, "join - no devices": { - sType: stringPtr("join"), + sType: test.StringPtr("join"), errsParamsRegex: "devices: ", urlFields: map[string]string{ "apikey": "bish"}, }, "join - valid": { - sType: stringPtr("join"), + sType: test.StringPtr("join"), urlFields: map[string]string{ "apikey": "bish"}, params: map[string]string{ "devices": "devices"}, }, "join - valid with main": { - sType: stringPtr("join"), + sType: test.StringPtr("join"), main: NewDefaults( "", nil, &map[string]string{ @@ -263,29 +263,29 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "apikey": "apikey"}), }, "mattermost - invalid": { - sType: stringPtr("mattermost"), + sType: test.StringPtr("mattermost"), errsURLFieldsRegex: "host: .*token: ", }, "mattermost - no host": { - sType: stringPtr("mattermost"), + sType: test.StringPtr("mattermost"), errsURLFieldsRegex: "host: ", urlFields: map[string]string{ "token": "bash"}, }, "mattermost - no token": { - sType: stringPtr("mattermost"), + sType: test.StringPtr("mattermost"), errsURLFieldsRegex: "token: ", urlFields: map[string]string{ "host": "bish"}, }, "mattermost - valid": { - sType: stringPtr("mattermost"), + sType: test.StringPtr("mattermost"), urlFields: map[string]string{ "host": "bish", "token": "bash"}, }, "mattermost - valid with main": { - sType: stringPtr("mattermost"), + sType: test.StringPtr("mattermost"), main: NewDefaults( "", nil, nil, &map[string]string{ @@ -293,29 +293,29 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "token": "bash"}), }, "matrix - invalid": { - sType: stringPtr("matrix"), + sType: test.StringPtr("matrix"), errsURLFieldsRegex: "host: .*password: ", }, "matrix - no host": { - sType: stringPtr("matrix"), + sType: test.StringPtr("matrix"), errsURLFieldsRegex: "host: ", urlFields: map[string]string{ "password": "bash"}, }, "matrix - no password": { - sType: stringPtr("matrix"), + sType: test.StringPtr("matrix"), errsURLFieldsRegex: "password: ", urlFields: map[string]string{ "host": "bish"}, }, "matrix - valid": { - sType: stringPtr("matrix"), + sType: test.StringPtr("matrix"), urlFields: map[string]string{ "host": "bish", "password": "password"}, }, "matrix - valid with main": { - sType: stringPtr("matrix"), + sType: test.StringPtr("matrix"), main: NewDefaults( "", nil, nil, &map[string]string{ @@ -323,54 +323,54 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "password": "bash"}), }, "ntfy - invalid": { - sType: stringPtr("ntfy"), + sType: test.StringPtr("ntfy"), errsURLFieldsRegex: "topic: ", }, "ntfy - valid": { - sType: stringPtr("ntfy"), + sType: test.StringPtr("ntfy"), urlFields: map[string]string{ "topic": "foo"}, }, "opsgenie - invalid": { - sType: stringPtr("opsgenie"), + sType: test.StringPtr("opsgenie"), errsURLFieldsRegex: "apikey: ", }, "opsgenie - valid": { - sType: stringPtr("opsgenie"), + sType: test.StringPtr("opsgenie"), urlFields: map[string]string{ "apikey": "apikey"}, }, "opsgenie - valid with main": { - sType: stringPtr("opsgenie"), + sType: test.StringPtr("opsgenie"), main: NewDefaults( "", nil, nil, &map[string]string{ "apikey": "apikey"}), }, "pushbullet - invalid": { - sType: stringPtr("pushbullet"), + sType: test.StringPtr("pushbullet"), errsURLFieldsRegex: "token: .*targets: ", }, "pushbullet - no token": { - sType: stringPtr("pushbullet"), + sType: test.StringPtr("pushbullet"), errsURLFieldsRegex: "token: ", urlFields: map[string]string{ "targets": "bash"}, }, "pushbullet - no targets": { - sType: stringPtr("pushbullet"), + sType: test.StringPtr("pushbullet"), errsURLFieldsRegex: "targets: ", urlFields: map[string]string{ "token": "bish"}, }, "pushbullet - valid": { - sType: stringPtr("pushbullet"), + sType: test.StringPtr("pushbullet"), urlFields: map[string]string{ "token": "bish", "targets": "targets"}, }, "pushbullet - valid with main": { - sType: stringPtr("pushbullet"), + sType: test.StringPtr("pushbullet"), main: NewDefaults( "", nil, nil, &map[string]string{ @@ -378,29 +378,29 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "targets": "bash"}), }, "pushover - invalid": { - sType: stringPtr("pushover"), + sType: test.StringPtr("pushover"), errsURLFieldsRegex: "token: .*user: ", }, "pushover - no token": { - sType: stringPtr("pushover"), + sType: test.StringPtr("pushover"), errsURLFieldsRegex: "token: ", urlFields: map[string]string{ "user": "bash"}, }, "pushover - no user": { - sType: stringPtr("pushover"), + sType: test.StringPtr("pushover"), errsURLFieldsRegex: "user: ", urlFields: map[string]string{ "token": "bish"}, }, "pushover - valid": { - sType: stringPtr("pushover"), + sType: test.StringPtr("pushover"), urlFields: map[string]string{ "token": "bish", "user": "user"}, }, "pushover - valid with main": { - sType: stringPtr("pushover"), + sType: test.StringPtr("pushover"), main: NewDefaults( "", nil, nil, &map[string]string{ @@ -408,11 +408,11 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "user": "bash"}), }, "rocketchat - invalid": { - sType: stringPtr("rocketchat"), + sType: test.StringPtr("rocketchat"), errsURLFieldsRegex: "host: .*tokena: .*tokenb: .*channel: ", }, "rocketchat - no host": { - sType: stringPtr("rocketchat"), + sType: test.StringPtr("rocketchat"), errsURLFieldsRegex: "host: ", urlFields: map[string]string{ "tokena": "bash", @@ -420,7 +420,7 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "channel": "bing"}, }, "rocketchat - no tokena": { - sType: stringPtr("rocketchat"), + sType: test.StringPtr("rocketchat"), errsURLFieldsRegex: "tokena: ", urlFields: map[string]string{ "host": "bish", @@ -428,7 +428,7 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "channel": "bing"}, }, "rocketchat - no tokenb": { - sType: stringPtr("rocketchat"), + sType: test.StringPtr("rocketchat"), errsURLFieldsRegex: "tokenb: ", urlFields: map[string]string{ "host": "bish", @@ -436,7 +436,7 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "channel": "bing"}, }, "rocketchat - no channel": { - sType: stringPtr("rocketchat"), + sType: test.StringPtr("rocketchat"), errsURLFieldsRegex: "channel: ", urlFields: map[string]string{ "host": "bish", @@ -444,7 +444,7 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "tokenb": "bosh"}, }, "rocketchat - valid": { - sType: stringPtr("rocketchat"), + sType: test.StringPtr("rocketchat"), urlFields: map[string]string{ "host": "bish", "tokena": "bash", @@ -452,7 +452,7 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "channel": "bing"}, }, "rocketchat - valid with main": { - sType: stringPtr("rocketchat"), + sType: test.StringPtr("rocketchat"), main: NewDefaults( "", nil, nil, &map[string]string{ @@ -462,29 +462,29 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "channel": "bing"}), }, "slack - invalid": { - sType: stringPtr("slack"), + sType: test.StringPtr("slack"), errsURLFieldsRegex: "token: .*channel: ", }, "slack - no token": { - sType: stringPtr("slack"), + sType: test.StringPtr("slack"), errsURLFieldsRegex: "token: ", urlFields: map[string]string{ "channel": "bash"}, }, "slack - no channel": { - sType: stringPtr("slack"), + sType: test.StringPtr("slack"), errsURLFieldsRegex: "channel: ", urlFields: map[string]string{ "token": "bish"}, }, "slack - valid": { - sType: stringPtr("slack"), + sType: test.StringPtr("slack"), urlFields: map[string]string{ "token": "bish", "channel": "channel"}, }, "slack - valid with main": { - sType: stringPtr("slack"), + sType: test.StringPtr("slack"), main: NewDefaults( "", nil, nil, &map[string]string{ @@ -492,11 +492,11 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "channel": "bash"}), }, "teams - invalid": { - sType: stringPtr("teams"), + sType: test.StringPtr("teams"), errsURLFieldsRegex: "group: .*tenant: .*altid: .*groupowner: ", errsParamsRegex: "host: ", }, "teams - no group": { - sType: stringPtr("teams"), + sType: test.StringPtr("teams"), errsURLFieldsRegex: "group: ", urlFields: map[string]string{ "tenant": "bash", @@ -506,7 +506,7 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "host": "https://release-argus.io"}, }, "teams - no tenant": { - sType: stringPtr("teams"), + sType: test.StringPtr("teams"), errsURLFieldsRegex: "tenant: ", urlFields: map[string]string{ "group": "bish", @@ -516,7 +516,7 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "host": "https://release-argus.io"}, }, "teams - no altid": { - sType: stringPtr("teams"), + sType: test.StringPtr("teams"), errsURLFieldsRegex: "altid: ", urlFields: map[string]string{ "group": "bish", @@ -526,7 +526,7 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "host": "https://release-argus.io"}, }, "teams - no groupowner": { - sType: stringPtr("teams"), + sType: test.StringPtr("teams"), errsURLFieldsRegex: "groupowner: ", urlFields: map[string]string{ "group": "bish", @@ -536,7 +536,7 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "host": "https://release-argus.io"}, }, "teams - no host": { - sType: stringPtr("teams"), + sType: test.StringPtr("teams"), errsParamsRegex: "host: ", urlFields: map[string]string{ "group": "bish", @@ -545,7 +545,7 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "groupowner": "bing"}, }, "teams - valid": { - sType: stringPtr("teams"), + sType: test.StringPtr("teams"), urlFields: map[string]string{ "group": "bish", "tenant": "bash", @@ -555,7 +555,7 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "host": "https://release-argus.io"}, }, "teams - valid with main": { - sType: stringPtr("teams"), + sType: test.StringPtr("teams"), main: NewDefaults( "", nil, &map[string]string{ @@ -567,32 +567,32 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "groupowner": "bing"}), }, "telegram - invalid": { - sType: stringPtr("telegram"), + sType: test.StringPtr("telegram"), errsURLFieldsRegex: "token: ", errsParamsRegex: "chats: ", }, "telegram - no token": { - sType: stringPtr("telegram"), + sType: test.StringPtr("telegram"), errsURLFieldsRegex: "token: ", urlFields: map[string]string{}, params: map[string]string{ "chats": "bash"}, }, "telegram - no chats": { - sType: stringPtr("telegram"), + sType: test.StringPtr("telegram"), errsParamsRegex: "chats: ", urlFields: map[string]string{ "token": "bish"}, }, "telegram - valid": { - sType: stringPtr("telegram"), + sType: test.StringPtr("telegram"), urlFields: map[string]string{ "token": "bish"}, params: map[string]string{ "chats": "chats"}, }, "telegram - valid with main": { - sType: stringPtr("telegram"), + sType: test.StringPtr("telegram"), main: NewDefaults( "", nil, &map[string]string{ @@ -601,39 +601,39 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "token": "bish"}), }, "zulip - invalid": { - sType: stringPtr("zulip"), + sType: test.StringPtr("zulip"), errsURLFieldsRegex: "host: .*botmail: .*botkey: ", }, "zulip - no host": { - sType: stringPtr("zulip"), + sType: test.StringPtr("zulip"), errsURLFieldsRegex: "host: ", urlFields: map[string]string{ "botmail": "bash", "botkey": "bosh"}, }, "zulip - no botmail": { - sType: stringPtr("zulip"), + sType: test.StringPtr("zulip"), errsURLFieldsRegex: "botmail: ", urlFields: map[string]string{ "host": "bish", "botkey": "bash"}, }, "zulip - no botkey": { - sType: stringPtr("zulip"), + sType: test.StringPtr("zulip"), errsURLFieldsRegex: "botkey: ", urlFields: map[string]string{ "host": "bish", "botmail": "bash"}, }, "zulip - valid": { - sType: stringPtr("zulip"), + sType: test.StringPtr("zulip"), urlFields: map[string]string{ "host": "bish", "botmail": "bash", "botkey": "bosh"}, }, "zulip - valid with main": { - sType: stringPtr("zulip"), + sType: test.StringPtr("zulip"), main: NewDefaults( "", nil, nil, &map[string]string{ @@ -642,23 +642,23 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "botkey": "bosh"}), }, "generic - invalid": { - sType: stringPtr("generic"), + sType: test.StringPtr("generic"), errsURLFieldsRegex: "host: ", }, "generic - valid": { - sType: stringPtr("generic"), + sType: test.StringPtr("generic"), urlFields: map[string]string{ "host": "example.com"}, }, "generic - valid with main": { - sType: stringPtr("generic"), + sType: test.StringPtr("generic"), main: NewDefaults( "", nil, nil, &map[string]string{ "host": "example.com"}), }, "generic - valid with custom_headers/json_payload_vars/query_vars": { - sType: stringPtr("generic"), + sType: test.StringPtr("generic"), urlFields: map[string]string{ "host": "example.com", "custom_headers": `{"foo":"bar"}`, @@ -666,37 +666,37 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "query_vars": `{"me":"work"}`}, }, "generic - invalid custom_headers": { - sType: stringPtr("generic"), + sType: test.StringPtr("generic"), errsURLFieldsRegex: `custom_headers: "[^ ]+ `, urlFields: map[string]string{ "host": "example.com", "custom_headers": `"foo":"bar"}`}, }, "generic - invalid json_payload_vars": { - sType: stringPtr("generic"), + sType: test.StringPtr("generic"), errsURLFieldsRegex: `json_payload_vars: "[^ ]+ `, urlFields: map[string]string{ "host": "example.com", "json_payload_vars": `{foo":"bar`}, }, "generic - invalid query_vars": { - sType: stringPtr("generic"), + sType: test.StringPtr("generic"), errsURLFieldsRegex: `query_vars: "[^ ]+ `, urlFields: map[string]string{ "host": "example.com", "query_vars": `{foo:bar}`}, }, "shoutrrr - invalid": { - sType: stringPtr("shoutrrr"), + sType: test.StringPtr("shoutrrr"), errsURLFieldsRegex: "raw: ", }, "shoutrrr - valid": { - sType: stringPtr("shoutrrr"), + sType: test.StringPtr("shoutrrr"), urlFields: map[string]string{ "raw": "bish"}, }, "shoutrrr - valid with main": { - sType: stringPtr("shoutrrr"), + sType: test.StringPtr("shoutrrr"), main: NewDefaults( "", nil, nil, &map[string]string{ @@ -720,7 +720,7 @@ func TestShoutrrr_checkValuesForType(t *testing.T) { "", "", "", "", "", "") svcStatus.Init( 1, 0, 0, - stringPtr("serviceID"), nil) + test.StringPtr("serviceID"), nil) shoutrrr.Init( svcStatus, tc.main, @@ -1286,7 +1286,7 @@ func TestShoutrrr_TestSend(t *testing.T) { "nil shoutrrr": { nilShoutrrr: true, wantErr: true}, "invalid type": { - sType: stringPtr("somethingUnknown"), wantErr: true}, + sType: test.StringPtr("somethingUnknown"), wantErr: true}, "valid": { wantErr: false}, } diff --git a/service/dashboard_test.go b/service/dashboard_test.go index 0e276368..15ba82a6 100644 --- a/service/dashboard_test.go +++ b/service/dashboard_test.go @@ -21,6 +21,7 @@ import ( "strings" "testing" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) @@ -34,16 +35,16 @@ func TestDashboardOptions_GetAutoApprove(t *testing.T) { }{ "root overrides all": { want: true, - root: boolPtr(true), - dfault: boolPtr(false), - hardDefault: boolPtr(false)}, + root: test.BoolPtr(true), + dfault: test.BoolPtr(false), + hardDefault: test.BoolPtr(false)}, "default overrides hardDefault": { want: true, - dfault: boolPtr(true), - hardDefault: boolPtr(false)}, + dfault: test.BoolPtr(true), + hardDefault: test.BoolPtr(false)}, "hardDefault is last resort": { want: true, - hardDefault: boolPtr(true)}, + hardDefault: test.BoolPtr(true)}, } for name, tc := range tests { diff --git a/service/deployed_version/gets_test.go b/service/deployed_version/gets_test.go index 9b77ee0e..f07e8242 100644 --- a/service/deployed_version/gets_test.go +++ b/service/deployed_version/gets_test.go @@ -19,6 +19,8 @@ package deployedver import ( "os" "testing" + + "github.com/release-argus/Argus/test" ) func TestLookup_GetAllowInvalidCerts(t *testing.T) { @@ -31,16 +33,16 @@ func TestLookup_GetAllowInvalidCerts(t *testing.T) { }{ "root overrides all": { wantBool: true, - root: boolPtr(true), - dfault: boolPtr(false), - hardDefault: boolPtr(false)}, + root: test.BoolPtr(true), + dfault: test.BoolPtr(false), + hardDefault: test.BoolPtr(false)}, "default overrides hardDefault": { wantBool: true, - dfault: boolPtr(true), - hardDefault: boolPtr(false)}, + dfault: test.BoolPtr(true), + hardDefault: test.BoolPtr(false)}, "hardDefault is last resort": { wantBool: true, - hardDefault: boolPtr(true)}, + hardDefault: test.BoolPtr(true)}, } for name, tc := range tests { diff --git a/service/deployed_version/help_test.go b/service/deployed_version/help_test.go index 50895bae..a237047d 100644 --- a/service/deployed_version/help_test.go +++ b/service/deployed_version/help_test.go @@ -22,15 +22,10 @@ import ( opt "github.com/release-argus/Argus/service/options" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) -func stringPtr(val string) *string { - return &val -} -func boolPtr(val bool) *bool { - return &val -} func TestMain(m *testing.M) { // initialize jLog jLog = util.NewJLog("DEBUG", false) @@ -45,17 +40,17 @@ func TestMain(m *testing.M) { func testLookup() (lookup *Lookup) { lookup = New( - boolPtr(true), + test.BoolPtr(true), nil, nil, "version", opt.New( - nil, "", boolPtr(true), + nil, "", test.BoolPtr(true), &opt.OptionsDefaults{}, - opt.NewDefaults("", boolPtr(true))), + opt.NewDefaults("", test.BoolPtr(true))), "", nil, &svcstatus.Status{ - ServiceID: stringPtr("test")}, + ServiceID: test.StringPtr("test")}, "https://invalid.release-argus.io/json", &LookupDefaults{}, &LookupDefaults{}) diff --git a/service/deployed_version/init_test.go b/service/deployed_version/init_test.go index d3cf0662..f88a661b 100644 --- a/service/deployed_version/init_test.go +++ b/service/deployed_version/init_test.go @@ -22,6 +22,7 @@ import ( "github.com/prometheus/client_golang/prometheus/testutil" opt "github.com/release-argus/Argus/service/options" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" metric "github.com/release-argus/Argus/web/metrics" ) @@ -80,7 +81,7 @@ func TestLookup_Init(t *testing.T) { lookup := testLookup() defaults := &LookupDefaults{} hardDefaults := &LookupDefaults{} - status := svcstatus.Status{ServiceID: stringPtr("TestInit")} + status := svcstatus.Status{ServiceID: test.StringPtr("TestInit")} var options opt.Options // WHEN Init is called on it diff --git a/service/deployed_version/query_test.go b/service/deployed_version/query_test.go index 4517c057..36b8f8bd 100644 --- a/service/deployed_version/query_test.go +++ b/service/deployed_version/query_test.go @@ -146,7 +146,7 @@ func TestLookup_Query(t *testing.T) { errRegex: "^$", url: "https://release-argus.io", regex: `([0-9]+)\s<[^>]+>(The) (Argus) (Developers)`, - regexTemplate: stringPtr("$2 $1 $4, $3"), + regexTemplate: test.StringPtr("$2 $1 $4, $3"), wantVersion: "The [0-9]+ Developers, Argus", }, "failing regex": { @@ -443,7 +443,7 @@ func TestLookup_Track(t *testing.T) { defer os.Unsetenv(k) } if tc.lookup != nil { - tc.lookup.AllowInvalidCerts = boolPtr(tc.allowInvalidCerts) + tc.lookup.AllowInvalidCerts = test.BoolPtr(tc.allowInvalidCerts) tc.lookup.BasicAuth = tc.basicAuth tc.lookup.Defaults = &LookupDefaults{} tc.lookup.HardDefaults = &LookupDefaults{} @@ -456,7 +456,7 @@ func TestLookup_Track(t *testing.T) { &announceChannel, &dbChannel, nil, "", "", "", "", "", "") tc.lookup.Status = svcStatus - tc.lookup.Status.ServiceID = stringPtr(name) + tc.lookup.Status.ServiceID = test.StringPtr(name) tc.lookup.Status.WebURL = &tc.lookup.URL if tc.deleting { tc.lookup.Status.SetDeleting() diff --git a/service/deployed_version/refresh_test.go b/service/deployed_version/refresh_test.go index 775bc4ba..7cd40038 100644 --- a/service/deployed_version/refresh_test.go +++ b/service/deployed_version/refresh_test.go @@ -24,6 +24,7 @@ import ( opt "github.com/release-argus/Argus/service/options" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) @@ -43,45 +44,45 @@ func TestBasicAuthFromString(t *testing.T) { want: &exampleBasicAuth, }, "empty string uses previous": { - basicAuth: stringPtr(""), + basicAuth: test.StringPtr(""), previous: &exampleBasicAuth, want: &exampleBasicAuth, }, "user and pass set": { - basicAuth: stringPtr(`{"username": "foo", "password": "bar"}`), + basicAuth: test.StringPtr(`{"username": "foo", "password": "bar"}`), previous: &exampleBasicAuth, want: &BasicAuth{ Username: "foo", Password: "bar"}, }, "only user set, get pass from previous": { - basicAuth: stringPtr(`{"username": "foo"}`), + basicAuth: test.StringPtr(`{"username": "foo"}`), previous: &exampleBasicAuth, want: &BasicAuth{ Username: "foo", Password: exampleBasicAuth.Password}, }, "only pass set, get user from previous": { - basicAuth: stringPtr(`{"password": "bar"}`), + basicAuth: test.StringPtr(`{"password": "bar"}`), previous: &exampleBasicAuth, want: &BasicAuth{ Username: exampleBasicAuth.Username, Password: "bar"}, }, "only user set, no previous": { - basicAuth: stringPtr(`{"username": "foo"}`), + basicAuth: test.StringPtr(`{"username": "foo"}`), previous: nil, want: &BasicAuth{ Username: "foo"}, }, "only pass set, no previous": { - basicAuth: stringPtr(`{"password": "bar"}`), + basicAuth: test.StringPtr(`{"password": "bar"}`), previous: nil, want: &BasicAuth{ Password: "bar"}, }, "invalid json": { - basicAuth: stringPtr(`{"username": false`), + basicAuth: test.StringPtr(`{"username": false`), previous: &exampleBasicAuth, want: &exampleBasicAuth, }, @@ -111,20 +112,20 @@ func TestHeadersFromString(t *testing.T) { want *[]Header }{ "invalid json": { - headers: stringPtr(`{"key": false, "value": "bash"}`), + headers: test.StringPtr(`{"key": false, "value": "bash"}`), want: &previousHeaders}, "nil string": { headers: nil, want: &previousHeaders}, "empty string": { - headers: stringPtr(""), + headers: test.StringPtr(""), want: &previousHeaders}, "single header": { - headers: stringPtr(`[{"key": "bish", "value": "bash"}]`), + headers: test.StringPtr(`[{"key": "bish", "value": "bash"}]`), want: &[]Header{ {Key: "bish", Value: "bash"}}}, "multiple headers": { - headers: stringPtr(`[{"key": "bish", "value": "bash"}, {"key": "bosh", "value": "bosh"}]`), + headers: test.StringPtr(`[{"key": "bish", "value": "bash"}, {"key": "bosh", "value": "bosh"}]`), want: &[]Header{ {Key: "bish", Value: "bash"}, {Key: "bosh", Value: "bosh"}}}, @@ -146,7 +147,7 @@ func TestHeadersFromString(t *testing.T) { } func TestLookup_ApplyOverrides(t *testing.T) { - test := testLookup() + testL := testLookup() // GIVEN various json strings to parse as parts of a Lookup tests := map[string]struct { allowInvalidCerts *string @@ -167,134 +168,134 @@ func TestLookup_ApplyOverrides(t *testing.T) { want: testLookup(), }, "allow invalid certs": { - allowInvalidCerts: stringPtr("false"), + allowInvalidCerts: test.StringPtr("false"), previous: testLookup(), want: New( - boolPtr(false), // AllowInvalidCerts + test.BoolPtr(false), // AllowInvalidCerts nil, nil, - test.JSON, - test.Options, + testL.JSON, + testL.Options, "", nil, &svcstatus.Status{}, - test.URL, + testL.URL, nil, nil), }, "basic auth": { - basicAuth: stringPtr(`{"username": "foo", "password": "bar"}`), + basicAuth: test.StringPtr(`{"username": "foo", "password": "bar"}`), previous: testLookup(), want: New( - test.AllowInvalidCerts, + testL.AllowInvalidCerts, &BasicAuth{ // BasicAuth Username: "foo", Password: "bar"}, nil, - test.JSON, - test.Options, + testL.JSON, + testL.Options, "", nil, &svcstatus.Status{}, - test.URL, + testL.URL, nil, nil), }, "headers": { - headers: stringPtr(`[{"key": "bish", "value": "bash"}, {"key": "bosh", "value": "bosh"}]`), + headers: test.StringPtr(`[{"key": "bish", "value": "bash"}, {"key": "bosh", "value": "bosh"}]`), previous: testLookup(), want: New( - test.AllowInvalidCerts, + testL.AllowInvalidCerts, nil, &[]Header{ // Headers {Key: "bish", Value: "bash"}, {Key: "bosh", Value: "bosh"}}, "version", - test.Options, + testL.Options, "", nil, &svcstatus.Status{}, - test.URL, + testL.URL, nil, nil), }, "json": { - json: stringPtr("bish"), + json: test.StringPtr("bish"), previous: testLookup(), want: New( - test.AllowInvalidCerts, + testL.AllowInvalidCerts, nil, nil, "bish", // JSON - test.Options, + testL.Options, "", nil, &svcstatus.Status{}, - test.URL, + testL.URL, nil, nil), }, "regex": { - regex: stringPtr("bish"), + regex: test.StringPtr("bish"), previous: testLookup(), want: New( - test.AllowInvalidCerts, + testL.AllowInvalidCerts, nil, nil, "version", - test.Options, + testL.Options, "bish", nil, // RegEx &svcstatus.Status{}, - test.URL, + testL.URL, nil, nil), }, "regex template": { - regexTemplate: stringPtr("$1.$4"), + regexTemplate: test.StringPtr("$1.$4"), previous: testLookup(), previousRegex: "([0-9]+)", want: New( - test.AllowInvalidCerts, + testL.AllowInvalidCerts, nil, nil, "version", - test.Options, + testL.Options, "([0-9]+)", - stringPtr("$1.$4"), // RegEx Template + test.StringPtr("$1.$4"), // RegEx Template &svcstatus.Status{}, - test.URL, + testL.URL, nil, nil), }, "semantic versioning": { - semanticVersioning: stringPtr("false"), + semanticVersioning: test.StringPtr("false"), previous: testLookup(), want: New( - test.AllowInvalidCerts, + testL.AllowInvalidCerts, nil, nil, - test.JSON, + testL.JSON, opt.New( - boolPtr(false), "", nil, + test.BoolPtr(false), "", nil, nil, nil), "", nil, &svcstatus.Status{}, - test.URL, + testL.URL, nil, nil), }, "url": { - url: stringPtr("https://valid.release-argus.io/json"), + url: test.StringPtr("https://valid.release-argus.io/json"), previous: testLookup(), want: New( - test.AllowInvalidCerts, + testL.AllowInvalidCerts, nil, nil, - test.JSON, - test.Options, + testL.JSON, + testL.Options, "", nil, &svcstatus.Status{}, "https://valid.release-argus.io/json", // URL nil, nil), }, "override with invalid (empty) url": { - url: stringPtr(""), + url: test.StringPtr(""), previous: testLookup(), want: nil, errRegex: "url: ", }, "override with invalid regex": { - regex: stringPtr("v([0-9))"), + regex: test.StringPtr("v([0-9))"), previous: testLookup(), want: nil, @@ -346,8 +347,8 @@ func TestLookup_ApplyOverrides(t *testing.T) { } func TestLookup_Refresh(t *testing.T) { - test := testLookup() - testVersion, _ := test.Query(true, &util.LogFrom{Primary: "TestRefresh"}) + testL := testLookup() + testVersion, _ := testL.Query(true, &util.LogFrom{Primary: "TestRefresh"}) if testVersion == "" { t.Fatalf("test version is empty") } @@ -370,38 +371,38 @@ func TestLookup_Refresh(t *testing.T) { announce bool }{ "Change of URL": { - url: stringPtr("https://valid.release-argus.io/json"), + url: test.StringPtr("https://valid.release-argus.io/json"), lookup: testLookup(), want: testVersion, }, "Removal of URL": { - url: stringPtr(""), + url: test.StringPtr(""), lookup: testLookup(), errRegex: "url: ", want: "", }, "Change of a few vars": { - json: stringPtr("otherVersion"), - semanticVersioning: stringPtr("false"), + json: test.StringPtr("otherVersion"), + semanticVersioning: test.StringPtr("false"), lookup: testLookup(), want: testVersion + "-beta", }, "Change of vars that fail Query": { - allowInvalidCerts: stringPtr("false"), + allowInvalidCerts: test.StringPtr("false"), lookup: testLookup(), errRegex: `x509 \(certificate invalid\)`, }, "Refresh new version": { lookup: New( - test.AllowInvalidCerts, + testL.AllowInvalidCerts, nil, nil, - test.JSON, - test.Options, + testL.JSON, + testL.Options, "", nil, &svcstatus.Status{}, - test.URL, - test.Defaults, - test.HardDefaults), + testL.URL, + testL.Defaults, + testL.HardDefaults), deployedVersion: "0.0.0", deployedVersionTimestamp: time.Now().UTC().Add(-time.Minute).Format(time.RFC3339), want: testVersion, @@ -416,7 +417,7 @@ func TestLookup_Refresh(t *testing.T) { // Copy the starting status previousStatus := svcstatus.Status{} if tc.lookup != nil { - tc.lookup.Status = &svcstatus.Status{ServiceID: stringPtr("serviceID")} + tc.lookup.Status = &svcstatus.Status{ServiceID: test.StringPtr("serviceID")} previousStatus.SetApprovedVersion(tc.lookup.Status.ApprovedVersion(), false) previousStatus.SetDeployedVersion(tc.lookup.Status.DeployedVersion(), false) previousStatus.SetDeployedVersionTimestamp(tc.lookup.Status.DeployedVersionTimestamp()) diff --git a/service/deployed_version/types_test.go b/service/deployed_version/types_test.go index c573556a..eb41a150 100644 --- a/service/deployed_version/types_test.go +++ b/service/deployed_version/types_test.go @@ -22,6 +22,7 @@ import ( opt "github.com/release-argus/Argus/service/options" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" ) func TestLookup_String(t *testing.T) { @@ -39,7 +40,7 @@ func TestLookup_String(t *testing.T) { }, "filled": { lookup: New( - boolPtr(false), + test.BoolPtr(false), &BasicAuth{ Username: "user", Password: "pass"}, &[]Header{ @@ -47,15 +48,15 @@ func TestLookup_String(t *testing.T) { {Key: "X-Another", Value: "val2"}}, "value.version", opt.New( - boolPtr(true), "9m", boolPtr(false), + test.BoolPtr(true), "9m", test.BoolPtr(false), nil, nil), - "v([0-9.]+)", stringPtr("$1"), + "v([0-9.]+)", test.StringPtr("$1"), &svcstatus.Status{}, "https://example.com", NewDefaults( - boolPtr(false)), + test.BoolPtr(false)), NewDefaults( - boolPtr(false))), + test.BoolPtr(false))), want: ` url: https://example.com allow_invalid_certs: false @@ -125,20 +126,20 @@ func TestLookup_IsEqual(t *testing.T) { "defaults ignored": { a: &Lookup{ Defaults: NewDefaults( - boolPtr(false))}, + test.BoolPtr(false))}, b: &Lookup{}, want: true, }, "hard_defaults ignored": { a: &Lookup{ HardDefaults: NewDefaults( - boolPtr(false))}, + test.BoolPtr(false))}, b: &Lookup{}, want: true, }, "equal": { a: New( - boolPtr(false), + test.BoolPtr(false), &BasicAuth{ Username: "user", Password: "pass"}, &[]Header{ @@ -148,15 +149,15 @@ func TestLookup_IsEqual(t *testing.T) { opt.New( nil, "", nil, nil, nil), - "v([0-9.]+)", stringPtr("$1"), + "v([0-9.]+)", test.StringPtr("$1"), &svcstatus.Status{}, "https://example.com", NewDefaults( - boolPtr(false)), + test.BoolPtr(false)), NewDefaults( - boolPtr(false))), + test.BoolPtr(false))), b: New( - boolPtr(false), + test.BoolPtr(false), &BasicAuth{ Username: "user", Password: "pass"}, &[]Header{ @@ -164,20 +165,20 @@ func TestLookup_IsEqual(t *testing.T) { {Key: "X-Another", Value: "val2"}}, "value.version", opt.New( - nil, "", boolPtr(true), + nil, "", test.BoolPtr(true), nil, nil), - "v([0-9.]+)", stringPtr("$1"), + "v([0-9.]+)", test.StringPtr("$1"), &svcstatus.Status{}, "https://example.com", NewDefaults( - boolPtr(false)), + test.BoolPtr(false)), NewDefaults( - boolPtr(false))), + test.BoolPtr(false))), want: true, }, "not equal": { a: New( - boolPtr(false), + test.BoolPtr(false), &BasicAuth{ Username: "user", Password: "pass"}, &[]Header{ @@ -185,17 +186,17 @@ func TestLookup_IsEqual(t *testing.T) { {Key: "X-Another", Value: "val2"}}, "value.version", opt.New( - nil, "", boolPtr(true), + nil, "", test.BoolPtr(true), nil, nil), - "v([0-9.]+)", stringPtr("$1"), + "v([0-9.]+)", test.StringPtr("$1"), &svcstatus.Status{}, "https://example.com", NewDefaults( - boolPtr(false)), + test.BoolPtr(false)), NewDefaults( - boolPtr(false))), + test.BoolPtr(false))), b: New( - boolPtr(false), + test.BoolPtr(false), &BasicAuth{ Username: "user", Password: "pass"}, &[]Header{ @@ -203,15 +204,15 @@ func TestLookup_IsEqual(t *testing.T) { {Key: "X-Another", Value: "val2"}}, "value.version", opt.New( - nil, "", boolPtr(true), + nil, "", test.BoolPtr(true), nil, nil), - "v([0-9.]+)", stringPtr("$1"), + "v([0-9.]+)", test.StringPtr("$1"), &svcstatus.Status{}, "https://example.com/other", NewDefaults( - boolPtr(false)), + test.BoolPtr(false)), NewDefaults( - boolPtr(false))), + test.BoolPtr(false))), want: false, }, "not equal with nil": { diff --git a/service/deployed_version/verify_test.go b/service/deployed_version/verify_test.go index 7f83d517..a403c8e8 100644 --- a/service/deployed_version/verify_test.go +++ b/service/deployed_version/verify_test.go @@ -20,6 +20,7 @@ import ( "regexp" "testing" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) @@ -62,7 +63,7 @@ func TestLookup_CheckValues(t *testing.T) { "regexTemplate with no regex": { url: "https://example.com", errRegex: `^$`, - regexTemplate: stringPtr("$1.$2.$3"), + regexTemplate: test.StringPtr("$1.$2.$3"), defaults: &LookupDefaults{}, }, "all errs": { diff --git a/service/handlers_test.go b/service/handlers_test.go index d4668a70..48f7af56 100644 --- a/service/handlers_test.go +++ b/service/handlers_test.go @@ -23,7 +23,9 @@ import ( command "github.com/release-argus/Argus/commands" deployedver "github.com/release-argus/Argus/service/deployed_version" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/webhook" + test_webhook "github.com/release-argus/Argus/webhook/test" ) func TestService_UpdateLatestApproved(t *testing.T) { @@ -44,7 +46,7 @@ func TestService_UpdateLatestApproved(t *testing.T) { } for name, tc := range tests { - svc := testServiceURL(name) + svc := testService(name, "url") t.Run(name, func(t *testing.T) { t.Parallel() @@ -99,7 +101,7 @@ func TestService_UpdatedVersion(t *testing.T) { commands: command.Slice{ {"true"}, {"false"}}, commandFails: []*bool{ - boolPtr(false), boolPtr(false)}, + test.BoolPtr(false), test.BoolPtr(false)}, }, "commands that haven't run fails doesn't announce or update deployed_version": { wantAnnounces: 0, @@ -107,7 +109,7 @@ func TestService_UpdatedVersion(t *testing.T) { commands: command.Slice{ {"true"}, {"false"}}, commandFails: []*bool{ - boolPtr(false), nil}, + test.BoolPtr(false), nil}, }, "commands that have failed doesn't announce or update deployed_version": { wantAnnounces: 0, @@ -115,7 +117,7 @@ func TestService_UpdatedVersion(t *testing.T) { commands: command.Slice{ {"true"}, {"false"}}, commandFails: []*bool{ - boolPtr(false), boolPtr(true)}, + test.BoolPtr(false), test.BoolPtr(true)}, }, "webhooks that have no fails does announce and update deployed_version": { wantAnnounces: 1, @@ -124,8 +126,8 @@ func TestService_UpdatedVersion(t *testing.T) { "0": {}, "1": {}}, webhookFails: map[string]*bool{ - "0": boolPtr(false), - "1": boolPtr(false)}, + "0": test.BoolPtr(false), + "1": test.BoolPtr(false)}, }, "webhooks that haven't run fails doesn't announce or update deployed_version": { wantAnnounces: 0, @@ -134,7 +136,7 @@ func TestService_UpdatedVersion(t *testing.T) { "0": {}, "1": {}}, webhookFails: map[string]*bool{ - "0": boolPtr(false), + "0": test.BoolPtr(false), "1": nil}, }, "webhooks that have failed doesn't announce or update deployed_version": { @@ -144,8 +146,8 @@ func TestService_UpdatedVersion(t *testing.T) { "0": {}, "1": {}}, webhookFails: map[string]*bool{ - "0": boolPtr(false), - "1": boolPtr(true)}, + "0": test.BoolPtr(false), + "1": test.BoolPtr(true)}, }, "commands and webhooks that have no fails does announce and update deployed_version": { wantAnnounces: 1, @@ -156,10 +158,10 @@ func TestService_UpdatedVersion(t *testing.T) { "0": {}, "1": {}}, commandFails: []*bool{ - boolPtr(false), boolPtr(false)}, + test.BoolPtr(false), test.BoolPtr(false)}, webhookFails: map[string]*bool{ - "0": boolPtr(false), - "1": boolPtr(false)}, + "0": test.BoolPtr(false), + "1": test.BoolPtr(false)}, }, "commands and webhooks that have no fails with deployedVersionLookup does announce and only update approved_version": { wantAnnounces: 1, @@ -172,10 +174,10 @@ func TestService_UpdatedVersion(t *testing.T) { "1": {}}, deployedVersion: &deployedver.Lookup{}, commandFails: []*bool{ - boolPtr(false), boolPtr(false)}, + test.BoolPtr(false), test.BoolPtr(false)}, webhookFails: map[string]*bool{ - "0": boolPtr(false), - "1": boolPtr(false)}, + "0": test.BoolPtr(false), + "1": test.BoolPtr(false)}, }, "deployedVersionLookup with no commands/webhooks doesn't announce or update deployed_version/approved_version": { wantAnnounces: 0, @@ -188,7 +190,7 @@ func TestService_UpdatedVersion(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - svc := testServiceURL(name) + svc := testService(name, "url") svc.Command = tc.commands svc.WebHook = tc.webhooks svc.Status.Init( @@ -254,21 +256,21 @@ func TestService_HandleUpdateActions(t *testing.T) { wantAnnounces: 1, deployedBecomesLatest: false, webhooks: webhook.Slice{ - "fail": testWebHook(true)}, + "fail": test_webhook.WebHook(true, false, false)}, }, "auto_approve and webhook that fails only announces the fail and doesn't update deployed_version": { autoApprove: true, wantAnnounces: 1, deployedBecomesLatest: false, webhooks: webhook.Slice{ - "fail": testWebHook(true)}, + "fail": test_webhook.WebHook(true, false, false)}, }, "auto_approve and webhook that passes announces the pass and version change and updates deployed_version": { autoApprove: true, wantAnnounces: 2, deployedBecomesLatest: true, webhooks: webhook.Slice{ - "pass": testWebHook(false)}, + "pass": test_webhook.WebHook(false, false, false)}, }, "auto_approve and command that fails only announces the fail and doesn't update deployed_version": { autoApprove: true, @@ -287,7 +289,7 @@ func TestService_HandleUpdateActions(t *testing.T) { } for name, tc := range tests { - svc := testServiceURL(name) + svc := testService(name, "url") svc.Command = tc.commands svc.WebHook = tc.webhooks svc.Status.Init( @@ -417,15 +419,15 @@ func TestService_HandleFailedActions(t *testing.T) { commands: command.Slice{ {"false"}, {"false"}}, webhooks: webhook.Slice{ - "will_fail": testWebHook(true)}, + "will_fail": test_webhook.WebHook(true, false, false)}, startFailsComand: []*bool{ nil, nil}, wantFailsCommand: []*bool{ - boolPtr(true), boolPtr(true)}, + test.BoolPtr(true), test.BoolPtr(true)}, startFailsWebHook: map[string]*bool{ "will_fail": nil}, wantFailsWebHook: map[string]*bool{ - "will_fail": boolPtr(true)}, + "will_fail": test.BoolPtr(true)}, }, "have command fails and no webhook fails retries only the failed commands": { wantAnnounces: 3, // 3 = 2 command pass, 1 command fail @@ -433,15 +435,15 @@ func TestService_HandleFailedActions(t *testing.T) { commands: command.Slice{ {"true"}, {"false"}, {"true"}, {"false"}}, webhooks: webhook.Slice{ - "pass": testWebHook(false)}, + "pass": test_webhook.WebHook(false, false, false)}, startFailsComand: []*bool{ - boolPtr(true), boolPtr(false), boolPtr(true), boolPtr(true)}, + test.BoolPtr(true), test.BoolPtr(false), test.BoolPtr(true), test.BoolPtr(true)}, wantFailsCommand: []*bool{ - boolPtr(false), boolPtr(false), boolPtr(false), boolPtr(true)}, + test.BoolPtr(false), test.BoolPtr(false), test.BoolPtr(false), test.BoolPtr(true)}, startFailsWebHook: map[string]*bool{ - "pass": boolPtr(false)}, + "pass": test.BoolPtr(false)}, wantFailsWebHook: map[string]*bool{ - "pass": boolPtr(false)}, + "pass": test.BoolPtr(false)}, }, "command fails before their next_runnable don't run": { wantAnnounces: 1, // 0 = no runs @@ -449,15 +451,15 @@ func TestService_HandleFailedActions(t *testing.T) { commands: command.Slice{ {"true"}, {"false"}, {"true"}, {"false"}}, webhooks: webhook.Slice{ - "pass": testWebHook(false)}, + "pass": test_webhook.WebHook(false, false, false)}, startFailsComand: []*bool{ - boolPtr(true), boolPtr(false), boolPtr(true), boolPtr(true)}, + test.BoolPtr(true), test.BoolPtr(false), test.BoolPtr(true), test.BoolPtr(true)}, wantFailsCommand: []*bool{ - boolPtr(false), boolPtr(false), boolPtr(true), boolPtr(true)}, + test.BoolPtr(false), test.BoolPtr(false), test.BoolPtr(true), test.BoolPtr(true)}, startFailsWebHook: map[string]*bool{ - "pass": boolPtr(false)}, + "pass": test.BoolPtr(false)}, wantFailsWebHook: map[string]*bool{ - "pass": boolPtr(false)}, + "pass": test.BoolPtr(false)}, commandNextRunnables: []time.Time{ time.Now().UTC(), time.Now().UTC(), @@ -470,12 +472,12 @@ func TestService_HandleFailedActions(t *testing.T) { commands: command.Slice{ {"true"}, {"false"}}, webhooks: webhook.Slice{ - "pass": testWebHook(false)}, - startFailsComand: []*bool{boolPtr(true), boolPtr(false)}, + "pass": test_webhook.WebHook(false, false, false)}, + startFailsComand: []*bool{test.BoolPtr(true), test.BoolPtr(false)}, wantFailsCommand: []*bool{ nil, nil}, startFailsWebHook: map[string]*bool{ - "pass": boolPtr(false)}, + "pass": test.BoolPtr(false)}, wantFailsWebHook: map[string]*bool{ "pass": nil}, }, @@ -484,21 +486,21 @@ func TestService_HandleFailedActions(t *testing.T) { deployedLatest: false, commands: command.Slice{{"false"}}, webhooks: webhook.Slice{ - "will_fail": testWebHook(true), - "will_pass": testWebHook(false), - "would_fail": testWebHook(true)}, + "will_fail": test_webhook.WebHook(true, false, false), + "will_pass": test_webhook.WebHook(false, false, false), + "would_fail": test_webhook.WebHook(true, false, false)}, startFailsComand: []*bool{ - boolPtr(false)}, + test.BoolPtr(false)}, wantFailsCommand: []*bool{ - boolPtr(false)}, + test.BoolPtr(false)}, startFailsWebHook: map[string]*bool{ - "will_fail": boolPtr(true), - "will_pass": boolPtr(true), - "would_fail": boolPtr(false)}, + "will_fail": test.BoolPtr(true), + "will_pass": test.BoolPtr(true), + "would_fail": test.BoolPtr(false)}, wantFailsWebHook: map[string]*bool{ - "will_fail": boolPtr(true), - "will_pass": boolPtr(false), - "would_fail": boolPtr(false)}, + "will_fail": test.BoolPtr(true), + "will_pass": test.BoolPtr(false), + "would_fail": test.BoolPtr(false)}, }, "webhook fails before their next_runnable don't run": { wantAnnounces: 1, // 0 runs @@ -506,21 +508,21 @@ func TestService_HandleFailedActions(t *testing.T) { commands: command.Slice{ {"false"}}, webhooks: webhook.Slice{ - "is_runnable": testWebHook(false), - "not_runnable": testWebHook(true), - "would_fail": testWebHook(true)}, + "is_runnable": test_webhook.WebHook(false, false, false), + "not_runnable": test_webhook.WebHook(true, false, false), + "would_fail": test_webhook.WebHook(true, false, false)}, startFailsComand: []*bool{ - boolPtr(false)}, + test.BoolPtr(false)}, wantFailsCommand: []*bool{ - boolPtr(false)}, + test.BoolPtr(false)}, startFailsWebHook: map[string]*bool{ - "is_runnable": boolPtr(true), - "not_runnable": boolPtr(true), - "would_fail": boolPtr(false)}, + "is_runnable": test.BoolPtr(true), + "not_runnable": test.BoolPtr(true), + "would_fail": test.BoolPtr(false)}, wantFailsWebHook: map[string]*bool{ - "is_runnable": boolPtr(false), - "not_runnable": boolPtr(true), - "would_fail": boolPtr(false)}, + "is_runnable": test.BoolPtr(false), + "not_runnable": test.BoolPtr(true), + "would_fail": test.BoolPtr(false)}, webhookNextRunnables: map[string]time.Time{ "is_runnable": time.Now().UTC(), "not_runnable": time.Now().UTC().Add(time.Minute)}, @@ -531,17 +533,17 @@ func TestService_HandleFailedActions(t *testing.T) { commands: command.Slice{ {"false"}}, webhooks: webhook.Slice{ - "will_pass0": testWebHook(false), - "will_pass1": testWebHook(false), - "would_fail": testWebHook(true)}, + "will_pass0": test_webhook.WebHook(false, false, false), + "will_pass1": test_webhook.WebHook(false, false, false), + "would_fail": test_webhook.WebHook(true, false, false)}, startFailsComand: []*bool{ - boolPtr(false)}, + test.BoolPtr(false)}, wantFailsCommand: []*bool{ nil}, startFailsWebHook: map[string]*bool{ - "will_pass0": boolPtr(true), - "will_pass1": boolPtr(true), - "would_fail": boolPtr(false)}, + "will_pass0": test.BoolPtr(true), + "will_pass1": test.BoolPtr(true), + "would_fail": test.BoolPtr(false)}, wantFailsWebHook: map[string]*bool{ "will_pass0": nil, "will_pass1": nil, @@ -550,7 +552,7 @@ func TestService_HandleFailedActions(t *testing.T) { } for name, tc := range tests { - svc := testServiceURL(name) + svc := testService(name, "url") t.Run(name, func(t *testing.T) { t.Parallel() @@ -605,7 +607,7 @@ func TestService_HandleFailedActions(t *testing.T) { time.Sleep(10 * time.Millisecond) if svc.Command != nil { for j := range svc.Command { - if stringifyPointer(svc.Status.Fails.Command.Get(j)) != stringifyPointer(tc.wantFailsCommand[j]) { + if test.StringifyPtr(svc.Status.Fails.Command.Get(j)) != test.StringifyPtr(tc.wantFailsCommand[j]) { actionsRan = false break } @@ -613,7 +615,7 @@ func TestService_HandleFailedActions(t *testing.T) { } if svc.WebHook != nil { for j := range svc.WebHook { - if stringifyPointer(svc.Status.Fails.WebHook.Get(j)) != stringifyPointer(tc.wantFailsWebHook[j]) { + if test.StringifyPtr(svc.Status.Fails.WebHook.Get(j)) != test.StringifyPtr(tc.wantFailsWebHook[j]) { actionsRan = false break } @@ -649,16 +651,16 @@ func TestService_HandleFailedActions(t *testing.T) { } // THEN the Command fails are as expected for i := range tc.wantFailsCommand { - if stringifyPointer(svc.Status.Fails.Command.Get(i)) != stringifyPointer(tc.wantFailsCommand[i]) { + if test.StringifyPtr(svc.Status.Fails.Command.Get(i)) != test.StringifyPtr(tc.wantFailsCommand[i]) { t.Errorf("got, command[%d]=%s, want %s", - i, stringifyPointer(svc.Status.Fails.Command.Get(i)), stringifyPointer(tc.wantFailsCommand[i])) + i, test.StringifyPtr(svc.Status.Fails.Command.Get(i)), test.StringifyPtr(tc.wantFailsCommand[i])) } } // THEN the WebHook fails are as expected for i := range tc.wantFailsWebHook { - if stringifyPointer(svc.Status.Fails.WebHook.Get(i)) != stringifyPointer(tc.wantFailsWebHook[i]) { + if test.StringifyPtr(svc.Status.Fails.WebHook.Get(i)) != test.StringifyPtr(tc.wantFailsWebHook[i]) { t.Errorf("got, webhook[%s]=%s, want %s", - i, stringifyPointer(svc.Status.Fails.WebHook.Get(i)), stringifyPointer(tc.wantFailsWebHook[i])) + i, test.StringifyPtr(svc.Status.Fails.WebHook.Get(i)), test.StringifyPtr(tc.wantFailsWebHook[i])) } } }) @@ -691,9 +693,9 @@ func TestService_HandleCommand(t *testing.T) { deployedLatest: true, deployedBecomesLatest: false, fails: []*bool{ - boolPtr(true)}, + test.BoolPtr(true)}, wantFails: []*bool{ - boolPtr(false)}, + test.BoolPtr(false)}, }, "Command that passed fails": { commands: command.Slice{{"false"}}, @@ -702,9 +704,9 @@ func TestService_HandleCommand(t *testing.T) { deployedLatest: true, deployedBecomesLatest: false, fails: []*bool{ - boolPtr(false)}, + test.BoolPtr(false)}, wantFails: []*bool{ - boolPtr(true)}, + test.BoolPtr(true)}, }, "Command that's not runnable doesn't run": { commands: command.Slice{{"false"}}, @@ -713,9 +715,9 @@ func TestService_HandleCommand(t *testing.T) { deployedLatest: true, deployedBecomesLatest: false, fails: []*bool{ - boolPtr(false)}, + test.BoolPtr(false)}, wantFails: []*bool{ - boolPtr(false)}, + test.BoolPtr(false)}, nextRunnable: time.Now().UTC().Add(time.Minute), }, "Command that's runnable does run": { @@ -725,15 +727,15 @@ func TestService_HandleCommand(t *testing.T) { deployedLatest: true, deployedBecomesLatest: false, fails: []*bool{ - boolPtr(false)}, + test.BoolPtr(false)}, wantFails: []*bool{ - boolPtr(true)}, + test.BoolPtr(true)}, nextRunnable: time.Now().UTC().Add(-time.Second), }, } for name, tc := range tests { - svc := testServiceURL(name) + svc := testService(name, "url") t.Run(name, func(t *testing.T) { t.Parallel() @@ -774,7 +776,7 @@ func TestService_HandleCommand(t *testing.T) { time.Sleep(10 * time.Millisecond) if svc.Command != nil { for j := range svc.Command { - if stringifyPointer(svc.Status.Fails.Command.Get(j)) != stringifyPointer(tc.wantFails[j]) { + if test.StringifyPtr(svc.Status.Fails.Command.Get(j)) != test.StringifyPtr(tc.wantFails[j]) { actionsRan = false break } @@ -803,7 +805,7 @@ func TestService_HandleCommand(t *testing.T) { tc.wantAnnounces, len(*svc.Status.AnnounceChannel)) fails := "" for i := range svc.Command { - fails += fmt.Sprintf("%d=%s, ", i, stringifyPointer(svc.Status.Fails.Command.Get(i))) + fails += fmt.Sprintf("%d=%s, ", i, test.StringifyPtr(svc.Status.Fails.Command.Get(i))) } t.Logf("commandFails: {%s}", fails[:len(fails)-2]) for len(*svc.Status.AnnounceChannel) != 0 { @@ -814,9 +816,9 @@ func TestService_HandleCommand(t *testing.T) { } // THEN the Command fails are as expected for i := range tc.wantFails { - if stringifyPointer(svc.Status.Fails.Command.Get(i)) != stringifyPointer(tc.wantFails[i]) { + if test.StringifyPtr(svc.Status.Fails.Command.Get(i)) != test.StringifyPtr(tc.wantFails[i]) { t.Errorf("got, command[%d]=%s, want %s", - i, stringifyPointer(svc.Status.Fails.Command.Get(i)), stringifyPointer(tc.wantFails[i])) + i, test.StringifyPtr(svc.Status.Fails.Command.Get(i)), test.StringifyPtr(tc.wantFails[i])) } } }) @@ -843,58 +845,58 @@ func TestService_HandleWebHook(t *testing.T) { }, "WebHook that failed passes": { webhooks: webhook.Slice{ - "pass": testWebHook(false)}, + "pass": test_webhook.WebHook(false, false, false)}, webhook: "pass", wantAnnounces: 1, deployedLatest: true, deployedBecomesLatest: false, fails: map[string]*bool{ - "pass": boolPtr(true)}, + "pass": test.BoolPtr(true)}, wantFails: map[string]*bool{ - "pass": boolPtr(false)}, + "pass": test.BoolPtr(false)}, }, "WebHook that passed fails": { webhooks: webhook.Slice{ - "fail": testWebHook(true)}, + "fail": test_webhook.WebHook(true, false, false)}, webhook: "fail", wantAnnounces: 1, deployedLatest: true, deployedBecomesLatest: false, fails: map[string]*bool{ - "fail": boolPtr(false)}, + "fail": test.BoolPtr(false)}, wantFails: map[string]*bool{ - "fail": boolPtr(true)}, + "fail": test.BoolPtr(true)}, }, "WebHook that's not runnable doesn't run": { webhooks: webhook.Slice{ - "pass": testWebHook(true)}, + "pass": test_webhook.WebHook(true, false, false)}, webhook: "pass", wantAnnounces: 0, deployedLatest: true, deployedBecomesLatest: false, fails: map[string]*bool{ - "pass": boolPtr(false)}, + "pass": test.BoolPtr(false)}, wantFails: map[string]*bool{ - "pass": boolPtr(false)}, + "pass": test.BoolPtr(false)}, nextRunnable: time.Now().UTC().Add(time.Minute), }, "WebHook that's runnable does run": { webhooks: webhook.Slice{ - "pass": testWebHook(false)}, + "pass": test_webhook.WebHook(false, false, false)}, webhook: "pass", wantAnnounces: 1, deployedLatest: true, deployedBecomesLatest: false, fails: map[string]*bool{ - "pass": boolPtr(true)}, + "pass": test.BoolPtr(true)}, wantFails: map[string]*bool{ - "pass": boolPtr(false)}, + "pass": test.BoolPtr(false)}, nextRunnable: time.Now().UTC().Add(-time.Second), }, } for name, tc := range tests { - svc := testServiceURL(name) + svc := testService(name, "url") svc.Status.Init( len(svc.Notify), len(tc.webhooks), 0, &svc.ID, @@ -930,7 +932,7 @@ func TestService_HandleWebHook(t *testing.T) { time.Sleep(10 * time.Millisecond) if svc.WebHook != nil { for j := range svc.WebHook { - if stringifyPointer(svc.Status.Fails.WebHook.Get(j)) != stringifyPointer(tc.wantFails[j]) { + if test.StringifyPtr(svc.Status.Fails.WebHook.Get(j)) != test.StringifyPtr(tc.wantFails[j]) { actionsRan = false break } @@ -959,7 +961,7 @@ func TestService_HandleWebHook(t *testing.T) { tc.wantAnnounces, len(*svc.Status.AnnounceChannel)) fails := "" for i := range svc.WebHook { - fails += fmt.Sprintf("%s=%s, ", i, stringifyPointer(svc.Status.Fails.WebHook.Get(i))) + fails += fmt.Sprintf("%s=%s, ", i, test.StringifyPtr(svc.Status.Fails.WebHook.Get(i))) } t.Logf("webhookFails: {%s}", fails[:len(fails)-2]) for len(*svc.Status.AnnounceChannel) != 0 { @@ -970,9 +972,9 @@ func TestService_HandleWebHook(t *testing.T) { } // THEN the WebHook fails are as expected for i := range tc.wantFails { - if stringifyPointer(svc.Status.Fails.WebHook.Get(i)) != stringifyPointer(tc.wantFails[i]) { + if test.StringifyPtr(svc.Status.Fails.WebHook.Get(i)) != test.StringifyPtr(tc.wantFails[i]) { t.Errorf("got, webhook[%s]=%s, want %s", - i, stringifyPointer(svc.Status.Fails.WebHook.Get(i)), stringifyPointer(tc.wantFails[i])) + i, test.StringifyPtr(svc.Status.Fails.WebHook.Get(i)), test.StringifyPtr(tc.wantFails[i])) } } }) @@ -1008,7 +1010,7 @@ func TestService_HandleSkip(t *testing.T) { } for name, tc := range tests { - svc := testServiceURL(name) + svc := testService(name, "url") t.Run(name, func(t *testing.T) { // t.Parallel() - cannot run in parallel as it uses the same channel @@ -1067,26 +1069,26 @@ func TestService_ShouldRetryAll(t *testing.T) { }, "commands that have failed": { command: []*bool{ - boolPtr(true), - boolPtr(true)}, + test.BoolPtr(true), + test.BoolPtr(true)}, want: false, }, "commands that have failed/haven't run": { command: []*bool{ - boolPtr(true), + test.BoolPtr(true), nil}, want: false, }, "commands that haven't failed": { command: []*bool{ - boolPtr(false), - boolPtr(false)}, + test.BoolPtr(false), + test.BoolPtr(false)}, want: true, }, "mix of all command fail states": { command: []*bool{ - boolPtr(true), - boolPtr(false), + test.BoolPtr(true), + test.BoolPtr(false), nil}, want: false, }, @@ -1098,51 +1100,51 @@ func TestService_ShouldRetryAll(t *testing.T) { }, "webhooks that have failed": { webhook: map[string]*bool{ - "1": boolPtr(true), - "2": boolPtr(true)}, + "1": test.BoolPtr(true), + "2": test.BoolPtr(true)}, want: false, }, "webhooks that have failed/haven't run": { webhook: map[string]*bool{ - "1": boolPtr(true), + "1": test.BoolPtr(true), "2": nil}, want: false, }, "webhooks that haven't failed": { webhook: map[string]*bool{ - "1": boolPtr(false), - "2": boolPtr(false)}, + "1": test.BoolPtr(false), + "2": test.BoolPtr(false)}, want: true, }, "mix of all webhook fail states": { webhook: map[string]*bool{ - "1": boolPtr(true), - "2": boolPtr(false), + "1": test.BoolPtr(true), + "2": test.BoolPtr(false), "3": nil}, want: false, }, "mix of all webhook and command fail states": { command: []*bool{ - boolPtr(true), boolPtr(false), nil}, + test.BoolPtr(true), test.BoolPtr(false), nil}, webhook: map[string]*bool{ - "1": boolPtr(true), - "2": boolPtr(false), + "1": test.BoolPtr(true), + "2": test.BoolPtr(false), "3": nil}, want: false, }, "mix of all webhook and command no fails": { command: []*bool{ - boolPtr(false), boolPtr(false), boolPtr(false)}, + test.BoolPtr(false), test.BoolPtr(false), test.BoolPtr(false)}, webhook: map[string]*bool{ - "1": boolPtr(false), - "2": boolPtr(false), - "3": boolPtr(false)}, + "1": test.BoolPtr(false), + "2": test.BoolPtr(false), + "3": test.BoolPtr(false)}, want: true, }, } for name, tc := range tests { - svc := testServiceURL(name) + svc := testService(name, "url") t.Run(name, func(t *testing.T) { t.Parallel() diff --git a/service/help_test.go b/service/help_test.go index 4724faad..01b488c4 100644 --- a/service/help_test.go +++ b/service/help_test.go @@ -17,9 +17,7 @@ package service import ( - "fmt" "os" - "strings" "testing" dbtype "github.com/release-argus/Argus/db/types" @@ -28,27 +26,10 @@ import ( "github.com/release-argus/Argus/service/latest_version/filter" opt "github.com/release-argus/Argus/service/options" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" - "github.com/release-argus/Argus/webhook" ) -func boolPtr(val bool) *bool { - return &val -} -func intPtr(val int) *int { - return &val -} -func stringPtr(val string) *string { - return &val -} -func stringifyPointer[T comparable](ptr *T) string { - str := "nil" - if ptr != nil { - str = fmt.Sprint(*ptr) - } - return str -} - func TestMain(m *testing.M) { // initialize jLog jLog = util.NewJLog("DEBUG", false) @@ -62,57 +43,7 @@ func TestMain(m *testing.M) { os.Exit(exitCode) } -func testServiceGitHub(id string) *Service { - var ( - announceChannel chan []byte = make(chan []byte, 2) - saveChannel chan bool = make(chan bool, 5) - databaseChannel chan dbtype.Message = make(chan dbtype.Message, 5) - ) - svc := &Service{ - ID: id, - LatestVersion: *latestver.New( - stringPtr(os.Getenv("GITHUB_TOKEN")), - nil, nil, nil, - &filter.Require{ - RegexContent: "content", - RegexVersion: "version"}, - nil, - "github", - "release-argus/Argus", - nil, - boolPtr(false), - &latestver.LookupDefaults{}, - &latestver.LookupDefaults{}), - Dashboard: *NewDashboardOptions( - boolPtr(false), "test", "https://example.com", "https://release-argus.io", - nil, nil), - Options: *opt.New( - boolPtr(true), "5s", boolPtr(true), - &opt.OptionsDefaults{}, &opt.OptionsDefaults{}), - Defaults: &Defaults{}, - HardDefaults: &Defaults{}, - } - // Status - svc.Status = *svcstatus.New( - &announceChannel, &databaseChannel, &saveChannel, - "", "", "", "", "", "") - svc.Status.ServiceID = &svc.ID - svc.Status.SetApprovedVersion("1.1.1", false) - svc.Status.SetLatestVersion("2.2.2", false) - svc.Status.SetLatestVersionTimestamp("2002-02-02T02:02:02Z") - svc.Status.SetDeployedVersion("0.0.0", false) - svc.Status.SetDeployedVersionTimestamp("2001-01-01T01:01:01Z") - - svc.Init( - &Defaults{}, &Defaults{}, - nil, nil, nil, - nil, nil, nil) - svc.Status.ServiceID = &svc.ID - svc.Status.WebURL = &svc.Dashboard.WebURL - return svc -} - -func testServiceURL(id string) *Service { +func testService(id string, sType string) *Service { var ( announceChannel = make(chan []byte, 5) saveChannel = make(chan bool, 5) @@ -120,16 +51,16 @@ func testServiceURL(id string) *Service { ) svc := &Service{ ID: id, - LatestVersion: *testLatestVersionLookupURL(false), + LatestVersion: *testLatestVersion(sType, false), DeployedVersionLookup: testDeployedVersionLookup(false), Dashboard: *NewDashboardOptions( - boolPtr(false), "test", "https://release-argus.io", "https://release-argus.io", + test.BoolPtr(false), "test", "https://release-argus.io", "https://release-argus.io", &DashboardOptionsDefaults{}, &DashboardOptionsDefaults{}), Status: *svcstatus.New( &announceChannel, &databaseChannel, &saveChannel, "", "", "", "", "", ""), Options: *opt.New( - boolPtr(true), "5s", boolPtr(true), + test.BoolPtr(true), "5s", test.BoolPtr(true), &opt.OptionsDefaults{}, &opt.OptionsDefaults{}), Defaults: &Defaults{}, HardDefaults: &Defaults{ @@ -150,10 +81,6 @@ func testServiceURL(id string) *Service { svc.Status.SetDeployedVersion("0.0.0", false) svc.Status.SetDeployedVersionTimestamp("2001-01-01T01:01:01Z") - svc.LatestVersion.Init( - &latestver.LookupDefaults{}, &latestver.LookupDefaults{}, - &svc.Status, - &svc.Options) svc.DeployedVersionLookup.Init( &deployedver.LookupDefaults{}, &deployedver.LookupDefaults{}, &svc.Status, @@ -161,13 +88,33 @@ func testServiceURL(id string) *Service { return svc } -func testLatestVersionLookupURL(fail bool) *latestver.Lookup { - lv := latestver.New( - stringPtr(os.Getenv("GITHUB_TOKEN")), - boolPtr(!fail), +func testLatestVersionGitHub(fail bool) (lv *latestver.Lookup) { + lv = latestver.New( + test.StringPtr(os.Getenv("GITHUB_TOKEN")), + nil, nil, nil, + &filter.Require{ + RegexContent: "content", + RegexVersion: "version"}, + nil, + "github", + "release-argus/Argus", + nil, + test.BoolPtr(false), + &latestver.LookupDefaults{}, + &latestver.LookupDefaults{}) + + if fail { + lv.AccessToken = test.StringPtr("invalid") + } + return +} +func testLatestVersionURL(fail bool) (lv *latestver.Lookup) { + lv = latestver.New( + nil, + test.BoolPtr(!fail), nil, opt.New( - nil, "", boolPtr(true), + nil, "", test.BoolPtr(true), &opt.OptionsDefaults{}, &opt.OptionsDefaults{}), &filter.Require{ RegexContent: "{{ version }}-beta", @@ -177,21 +124,31 @@ func testLatestVersionLookupURL(fail bool) *latestver.Lookup { "url", "https://invalid.release-argus.io/plain", &filter.URLCommandSlice{ - {Type: "regex", Regex: stringPtr("v([0-9.]+)")}}, - boolPtr(false), + {Type: "regex", Regex: test.StringPtr("v([0-9.]+)")}}, + test.BoolPtr(false), &latestver.LookupDefaults{}, &latestver.LookupDefaults{}) - lv.Status.ServiceID = stringPtr("foo") + + return +} + +func testLatestVersion(lvType string, fail bool) (lv *latestver.Lookup) { + if lvType == "url" { + lv = testLatestVersionURL(fail) + } else { + lv = testLatestVersionGitHub(fail) + } + lv.Status.ServiceID = test.StringPtr("TEST_LV") return lv } func testDeployedVersionLookup(fail bool) (dvl *deployedver.Lookup) { dvl = deployedver.New( - boolPtr(!fail), + test.BoolPtr(!fail), nil, nil, "version", opt.New( - nil, "", boolPtr(true), + nil, "", test.BoolPtr(true), &opt.OptionsDefaults{}, &opt.OptionsDefaults{}), "", nil, &svcstatus.Status{}, @@ -208,34 +165,3 @@ func testDeployedVersionLookup(fail bool) (dvl *deployedver.Lookup) { return } - -func testWebHook(failing bool) *webhook.WebHook { - desiredStatusCode := 0 - whMaxTries := uint(1) - wh := webhook.New( - boolPtr(false), - nil, - "0s", - &desiredStatusCode, - nil, - &whMaxTries, - nil, - stringPtr("12m"), - "argus", - boolPtr(false), - "github", - "https://valid.release-argus.io/hooks/github-style", - nil, nil, nil) - if failing { - wh.Secret = "notArgus" - } - return wh -} - -func trimJSON(str string) string { - str = strings.TrimSpace(str) - str = strings.ReplaceAll(str, "\n", "") - str = strings.ReplaceAll(str, "\t", "") - str = strings.ReplaceAll(str, ": ", ":") - return str -} diff --git a/service/init_test.go b/service/init_test.go index 4364ff26..f86f1ed6 100644 --- a/service/init_test.go +++ b/service/init_test.go @@ -25,11 +25,12 @@ import ( latestver "github.com/release-argus/Argus/service/latest_version" "github.com/release-argus/Argus/util" "github.com/release-argus/Argus/webhook" + test_webhook "github.com/release-argus/Argus/webhook/test" ) func TestService_ServiceInfo(t *testing.T) { // GIVEN a Service - svc := testServiceURL("TestServiceInfo") + svc := testService("TestServiceInfo", "url") id := "test_id" svc.ID = id url := "https://test_url.com" @@ -123,7 +124,7 @@ func TestService_IconURL(t *testing.T) { } for name, tc := range tests { - svc := testServiceGitHub(name) + svc := testService(name, "github") t.Run(name, func(t *testing.T) { t.Parallel() @@ -168,7 +169,7 @@ func TestService_Init(t *testing.T) { Command: command.Slice{ {"ls"}}, WebHook: webhook.Slice{ - "test": testWebHook(false)}}, + "test": test_webhook.WebHook(false, false, false)}}, }, "service with notifys from defaults": { svc: &Service{ @@ -225,7 +226,7 @@ func TestService_Init(t *testing.T) { LatestVersion: latestver.Lookup{ Type: "github", URL: "release-argus/Argus"}, WebHook: webhook.Slice{ - "test": testWebHook(false)}}, + "test": test_webhook.WebHook(false, false, false)}}, defaults: &Defaults{ WebHook: map[string]struct{}{ "bar": {}}}, diff --git a/service/latest_version/api_type/types_test.go b/service/latest_version/api_type/types_test.go index a390d355..c77b4fb6 100644 --- a/service/latest_version/api_type/types_test.go +++ b/service/latest_version/api_type/types_test.go @@ -20,6 +20,7 @@ import ( "testing" "github.com/Masterminds/semver/v3" + "github.com/release-argus/Argus/test" ) func TestRelease_String(t *testing.T) { @@ -70,7 +71,7 @@ func TestRelease_String(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - tc.want = trimJSON(tc.want) + tc.want = test.TrimJSON(tc.want) if tc.release_semantic_version != "" { tc.release.SemanticVersion, _ = semver.NewVersion(tc.release_semantic_version) } @@ -114,7 +115,7 @@ func TestAsset_String(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - tc.want = trimJSON(tc.want) + tc.want = test.TrimJSON(tc.want) // WHEN the Asset is stringified with String got := tc.asset.String() diff --git a/service/latest_version/filter/command_test.go b/service/latest_version/filter/command_test.go index d22aab59..8be0925c 100644 --- a/service/latest_version/filter/command_test.go +++ b/service/latest_version/filter/command_test.go @@ -22,6 +22,7 @@ import ( command "github.com/release-argus/Argus/commands" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) @@ -52,7 +53,7 @@ func TestRequire_ExecCommand(t *testing.T) { require.Status.Init( 0, 1, 0, &name, - stringPtr("http://example.com")) + test.StringPtr("http://example.com")) // WHEN ApplyTemplate is called on the Command err := require.ExecCommand(&util.LogFrom{}) diff --git a/service/latest_version/filter/docker_test.go b/service/latest_version/filter/docker_test.go index bccc0312..a1e8d793 100644 --- a/service/latest_version/filter/docker_test.go +++ b/service/latest_version/filter/docker_test.go @@ -24,6 +24,7 @@ import ( "testing" "time" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) @@ -157,7 +158,7 @@ func TestDockerCheck_getQueryToken(t *testing.T) { "", time.Now().UTC().Add(time.Minute), nil), hadQueryToken: base64.StdEncoding.EncodeToString([]byte("foo")), - wantQueryToken: stringPtr( + wantQueryToken: test.StringPtr( base64.StdEncoding.EncodeToString([]byte("foo"))), }, "Gets token if past validUntil": { @@ -483,7 +484,7 @@ func TestDockerCheck_SetQueryToken(t *testing.T) { "tokenHub", "", "tokenQuay", nil)), - defaultTokenGHCR: stringPtr(""), + defaultTokenGHCR: test.StringPtr(""), setForToken: "tokenGHCR", changeDefaults: false, }, @@ -705,8 +706,8 @@ func TestDockerCheckDefaults_setQueryToken(t *testing.T) { "defaultTokenForHub", "", "defaultTokenForQuay", nil)), - ghcrToken: stringPtr(""), - ghcrDefaultToken: stringPtr(""), + ghcrToken: test.StringPtr(""), + ghcrDefaultToken: test.StringPtr(""), setForType: "ghcr", setForToken: "", changeDefaults: false, diff --git a/service/latest_version/filter/help_test.go b/service/latest_version/filter/help_test.go index ecca38d3..b29e01db 100644 --- a/service/latest_version/filter/help_test.go +++ b/service/latest_version/filter/help_test.go @@ -25,10 +25,6 @@ import ( "github.com/release-argus/Argus/util" ) -func stringPtr(val string) *string { - return &val -} - func TestMain(m *testing.M) { // initialize jLog jLog = util.NewJLog("DEBUG", false) @@ -55,9 +51,9 @@ func testURLCommandRegexTemplate() URLCommand { index := 0 template := "_$1_" return URLCommand{ - Type: "regex", - Regex: ®ex, - Index: index, + Type: "regex", + Regex: ®ex, + Index: index, Template: &template} } diff --git a/service/latest_version/filter/require_test.go b/service/latest_version/filter/require_test.go index becc800c..b8d3d2f3 100644 --- a/service/latest_version/filter/require_test.go +++ b/service/latest_version/filter/require_test.go @@ -24,6 +24,7 @@ import ( command "github.com/release-argus/Argus/commands" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) @@ -47,8 +48,8 @@ func TestRequire_Init(t *testing.T) { status := svcstatus.Status{} status.Init( 0, 0, 0, - stringPtr("test"), - stringPtr("http://example.com")) + test.StringPtr("test"), + test.StringPtr("http://example.com")) status.SetDeployedVersion("1.2.3", false) defaults := RequireDefaults{ Docker: *NewDockerCheckDefaults( @@ -275,7 +276,7 @@ func TestRequire_FromStr(t *testing.T) { pointerToDefault bool }{ "nil": { - jsonStr: stringPtr(""), + jsonStr: test.StringPtr(""), errRegex: "EOF$", want: nil, }, @@ -285,49 +286,49 @@ func TestRequire_FromStr(t *testing.T) { pointerToDefault: true, }, "empty": { - jsonStr: stringPtr("{}"), + jsonStr: test.StringPtr("{}"), want: nil, }, "empty with default": { - jsonStr: stringPtr("{}"), + jsonStr: test.StringPtr("{}"), pointerToDefault: true, }, "invalid JSON": { - jsonStr: stringPtr("{"), + jsonStr: test.StringPtr("{"), errRegex: `unexpected EOF$`, }, "invalid JSON with default": { - jsonStr: stringPtr("{"), + jsonStr: test.StringPtr("{"), dflt: &dflt, pointerToDefault: true, errRegex: `unexpected EOF$`, }, "invalid data type": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "regex_content": 1}`), errRegex: `json: cannot unmarshal number into Go struct field Require.regex_content of type string$`, }, "invalid data type with default": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "regex_content": 1}`), dflt: &dflt, pointerToDefault: true, errRegex: `json: cannot unmarshal number into Go struct field Require.regex_content of type string$`, }, "RegexContent defined": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "regex_content": "foo"}`), want: &Require{ RegexContent: "foo"}, }, "RegexVersion defined": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "regex_version": "foo"}`), want: &Require{ RegexVersion: "foo"}, }, "RegexContent from str, RegexVersion from default": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "regex_content": "foo"}`), dflt: &Require{ RegexVersion: "bar"}, @@ -336,7 +337,7 @@ func TestRequire_FromStr(t *testing.T) { RegexVersion: "bar"}, }, "RegexContent from default, RegexVersion from str": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "regex_version": "bar"}`), dflt: &Require{ RegexContent: "foo"}, @@ -345,14 +346,14 @@ func TestRequire_FromStr(t *testing.T) { RegexVersion: "bar"}, }, "Command defined": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "command":[ "foo", "bar"]}`), want: &Require{Command: []string{"foo", "bar"}}, }, "No Command JSON uses default": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "regex_version": "foo"}`), dflt: &Require{ RegexVersion: "bar", @@ -362,7 +363,7 @@ func TestRequire_FromStr(t *testing.T) { Command: []string{"foo", "bar"}}, }, "Empty command overrides default": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "regex_version": "foo", "command": []}`), dflt: &Require{ @@ -373,14 +374,14 @@ func TestRequire_FromStr(t *testing.T) { Command: []string{}}, }, "Only Docker.Type sent": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "docker": { "type": "ghcr"}}`), want: &Require{}, errRegex: "^$", }, "Docker defined, none prior": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "docker": { "type": "ghcr", "image": "release-argus/argus", @@ -397,7 +398,7 @@ func TestRequire_FromStr(t *testing.T) { "", time.Time{}, nil)}, }, "Docker changing Type": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "docker": { "type": "ghcr"}}`), dflt: &Require{ @@ -418,7 +419,7 @@ func TestRequire_FromStr(t *testing.T) { "", time.Time{}, nil)}, }, "Docker changing Image": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "docker": { "image": "release-argus/argus"}}`), dflt: &Require{ @@ -441,7 +442,7 @@ func TestRequire_FromStr(t *testing.T) { nil)}, }, "Docker changing Tag": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "docker": { "tag": "1.2.3"}}`), dflt: &Require{ @@ -464,7 +465,7 @@ func TestRequire_FromStr(t *testing.T) { nil)}, }, "Docker changing Username": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "docker": { "username": "sir"}}`), dflt: &Require{ @@ -486,7 +487,7 @@ func TestRequire_FromStr(t *testing.T) { "", time.Time{}, nil)}, }, "Docker changing Token": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "docker": { "token": "letmein"}}`), dflt: &Require{ @@ -507,7 +508,7 @@ func TestRequire_FromStr(t *testing.T) { "", time.Time{}, nil)}, }, "Docker changing multiple (GHCR Argus)": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "docker": { "type": "ghcr", "image": "release-argus/argus", @@ -532,7 +533,7 @@ func TestRequire_FromStr(t *testing.T) { "", time.Time{}, nil)}, }, "only RegexContent changed keeps default Docker": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "regex_content": "foo"}`), dflt: &Require{Docker: NewDockerCheck( "ghcr", @@ -552,7 +553,7 @@ func TestRequire_FromStr(t *testing.T) { nil)}, }, "Invalid Docker (no tag)": { - jsonStr: stringPtr(`{ + jsonStr: test.StringPtr(`{ "docker": { "type": "ghcr", "image": "release-argus/argus"}}`), diff --git a/service/latest_version/filter/urlcommand_test.go b/service/latest_version/filter/urlcommand_test.go index e1cb08ba..96fdf5ce 100644 --- a/service/latest_version/filter/urlcommand_test.go +++ b/service/latest_version/filter/urlcommand_test.go @@ -21,6 +21,7 @@ import ( "strings" "testing" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" "gopkg.in/yaml.v3" ) @@ -113,34 +114,34 @@ func TestURLCommandsFromStr(t *testing.T) { want *URLCommandSlice }{ "regex - invalid": { - jsonStr: stringPtr(`[{"type":"regex","regex":"-([0-9.+)-"}]`), + jsonStr: test.StringPtr(`[{"type":"regex","regex":"-([0-9.+)-"}]`), want: &defaults, errRegex: `regex:.*\(Invalid RegEx\)`, }, "regex": { - jsonStr: stringPtr(`[{"type":"regex","regex":"-([0-9.]+)-"}]`), + jsonStr: test.StringPtr(`[{"type":"regex","regex":"-([0-9.]+)-"}]`), want: &URLCommandSlice{ testURLCommandRegex()}, }, "replace": { - jsonStr: stringPtr(`[{"type":"replace","old":"foo","new":"bar"}]`), + jsonStr: test.StringPtr(`[{"type":"replace","old":"foo","new":"bar"}]`), want: &URLCommandSlice{ testURLCommandReplace()}, }, "split": { - jsonStr: stringPtr(`[{"type":"split","text":"this","index":1}]`), + jsonStr: test.StringPtr(`[{"type":"split","text":"this","index":1}]`), want: &URLCommandSlice{ testURLCommandSplit()}, }, "all types": { - jsonStr: stringPtr(`[{"type":"regex","regex":"-([0-9.]+)-"},{"type":"replace","old":"foo","new":"bar"},{"type":"split","text":"this","index":1}]`), + jsonStr: test.StringPtr(`[{"type":"regex","regex":"-([0-9.]+)-"},{"type":"replace","old":"foo","new":"bar"},{"type":"split","text":"this","index":1}]`), want: &URLCommandSlice{ testURLCommandRegex(), testURLCommandReplace(), testURLCommandSplit()}, }, "multiple of the each type": { - jsonStr: stringPtr(`[{"type":"regex","regex":"-([0-9.]+)-"},{"type":"regex","regex":"-([0-9.]+)-"},{"type":"replace","old":"foo","new":"bar"},{"type":"replace","old":"foo","new":"bar"},{"type":"split","text":"this","index":1},{"type":"split","text":"this","index":1}]`), + jsonStr: test.StringPtr(`[{"type":"regex","regex":"-([0-9.]+)-"},{"type":"regex","regex":"-([0-9.]+)-"},{"type":"replace","old":"foo","new":"bar"},{"type":"replace","old":"foo","new":"bar"},{"type":"split","text":"this","index":1},{"type":"split","text":"this","index":1}]`), want: &URLCommandSlice{ testURLCommandRegex(), testURLCommandRegex(), @@ -150,11 +151,11 @@ func TestURLCommandsFromStr(t *testing.T) { testURLCommandSplit()}, }, "empty": { - jsonStr: stringPtr(`[]`), + jsonStr: test.StringPtr(`[]`), want: &URLCommandSlice{}, }, "object rather than list": { - jsonStr: stringPtr(`{"type":"regex"}`), + jsonStr: test.StringPtr(`{"type":"regex"}`), errRegex: "cannot unmarshal object", want: &defaults, }, @@ -219,76 +220,76 @@ func TestURLCommandSlice_Run(t *testing.T) { }, "regex": { slice: &URLCommandSlice{ - {Type: "regex", Regex: stringPtr("([a-z]+)[0-9]+"), Index: 1}}, + {Type: "regex", Regex: test.StringPtr("([a-z]+)[0-9]+"), Index: 1}}, errRegex: "^$", want: "def", }, "regex with negative index": { slice: &URLCommandSlice{ - {Type: "regex", Regex: stringPtr("([a-z]+)[0-9]+"), Index: -1}}, + {Type: "regex", Regex: test.StringPtr("([a-z]+)[0-9]+"), Index: -1}}, errRegex: "^$", want: "def", }, "regex doesn't match (gives text that didn't match)": { slice: &URLCommandSlice{ - {Type: "regex", Regex: stringPtr("([h-z]+)[0-9]+"), Index: 1}}, + {Type: "regex", Regex: test.StringPtr("([h-z]+)[0-9]+"), Index: 1}}, errRegex: `regex .* didn't return any matches on "` + testText + `"`, want: testText, }, "regex doesn't match (doesn't give text that didn't match as too long)": { slice: &URLCommandSlice{ - {Type: "regex", Regex: stringPtr("([h-z]+)[0-9]+"), Index: 1}}, + {Type: "regex", Regex: test.StringPtr("([h-z]+)[0-9]+"), Index: 1}}, errRegex: "regex .* didn't return any matches$", text: strings.Repeat("a123", 5), want: "a123a123a123a123a123", }, "regex index out of bounds": { slice: &URLCommandSlice{ - {Type: "regex", Regex: stringPtr("([a-z]+)[0-9]+"), Index: 2}}, + {Type: "regex", Regex: test.StringPtr("([a-z]+)[0-9]+"), Index: 2}}, errRegex: `regex .* returned \d elements on "[^']+", but the index wants element number \d`, want: testText, }, "regex with template": { slice: &URLCommandSlice{ - {Type: "regex", Regex: stringPtr("([a-z]+)([0-9]+)"), Index: 1, Template: stringPtr("$1_$2")}}, + {Type: "regex", Regex: test.StringPtr("([a-z]+)([0-9]+)"), Index: 1, Template: test.StringPtr("$1_$2")}}, errRegex: "^$", want: "def_456", }, "replace": { slice: &URLCommandSlice{ - {Type: "replace", Old: stringPtr("-"), New: stringPtr(" ")}}, + {Type: "replace", Old: test.StringPtr("-"), New: test.StringPtr(" ")}}, errRegex: "^$", want: "abc123 def456", }, "split": { slice: &URLCommandSlice{ - {Type: "split", Text: stringPtr("-"), Index: -1}}, + {Type: "split", Text: test.StringPtr("-"), Index: -1}}, errRegex: "^$", want: "def456", }, "split with negative index": { slice: &URLCommandSlice{ - {Type: "split", Text: stringPtr("-"), Index: 0}}, + {Type: "split", Text: test.StringPtr("-"), Index: 0}}, errRegex: "^$", want: "abc123", }, "split on unknown text": { slice: &URLCommandSlice{ - {Type: "split", Text: stringPtr("7"), Index: 0}}, + {Type: "split", Text: test.StringPtr("7"), Index: 0}}, errRegex: "split didn't find any .* to split on", want: testText, }, "split index out of bounds": { slice: &URLCommandSlice{ - {Type: "split", Text: stringPtr("-"), Index: 2}}, + {Type: "split", Text: test.StringPtr("-"), Index: 2}}, errRegex: `split .* returned \d elements on "[^']+", but the index wants element number \d`, want: testText, }, "all types": { slice: &URLCommandSlice{ - {Type: "regex", Regex: stringPtr("([a-z]+)[0-9]+"), Index: 1}, - {Type: "replace", Old: stringPtr("e"), New: stringPtr("a")}, - {Type: "split", Text: stringPtr("a"), Index: 1}}, + {Type: "regex", Regex: test.StringPtr("([a-z]+)[0-9]+"), Index: 1}, + {Type: "replace", Old: test.StringPtr("e"), New: test.StringPtr("a")}, + {Type: "split", Text: test.StringPtr("a"), Index: 1}}, errRegex: "^$", want: "f", }, @@ -398,7 +399,7 @@ func TestURLCommandSlice_CheckValues(t *testing.T) { }, "invalid regex": { slice: &URLCommandSlice{ - {Type: "regex", Regex: stringPtr("[0-")}}, + {Type: "regex", Regex: test.StringPtr("[0-")}}, errRegex: []string{`^ regex: .* `}, }, "valid regex with template": { @@ -407,9 +408,9 @@ func TestURLCommandSlice_CheckValues(t *testing.T) { }, "valid regex with empty template": { slice: &URLCommandSlice{ - {Type: "regex", Regex: stringPtr("[0-"), Template: stringPtr("")}}, + {Type: "regex", Regex: test.StringPtr("[0-"), Template: test.StringPtr("")}}, wantSlice: &URLCommandSlice{ - {Type: "regex", Regex: stringPtr("[0-")}}, + {Type: "regex", Regex: test.StringPtr("[0-")}}, errRegex: []string{`^$`}, }, "valid replace": { @@ -525,8 +526,8 @@ old: was new: now`, slice: URLCommandSlice{ {Type: "regex", - Regex: stringPtr("foo"), Index: 1, - Text: stringPtr("hi"), Old: stringPtr("was"), New: stringPtr("now")}}, + Regex: test.StringPtr("foo"), Index: 1, + Text: test.StringPtr("hi"), Old: test.StringPtr("was"), New: test.StringPtr("now")}}, errRegex: "^$", }, "list of URLCommands": { @@ -542,9 +543,9 @@ new: now`, errRegex: "^$", slice: URLCommandSlice{ {Type: "regex", - Regex: stringPtr(`\"([0-9.+])\"`), Index: 1}, - {Type: "replace", Old: stringPtr("foo"), New: stringPtr("bar")}, - {Type: "split", Text: stringPtr("abc"), Index: 2}}, + Regex: test.StringPtr(`\"([0-9.+])\"`), Index: 1}, + {Type: "replace", Old: test.StringPtr("foo"), New: test.StringPtr("bar")}, + {Type: "split", Text: test.StringPtr("abc"), Index: 2}}, }, } diff --git a/service/latest_version/gets_test.go b/service/latest_version/gets_test.go index 75bc429b..95dd1a01 100644 --- a/service/latest_version/gets_test.go +++ b/service/latest_version/gets_test.go @@ -21,6 +21,7 @@ import ( "testing" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" ) func TestLookup_GetAccessToken(t *testing.T) { @@ -34,35 +35,35 @@ func TestLookup_GetAccessToken(t *testing.T) { }{ "root overrides all": { wantString: "this", - root: stringPtr("this"), - dfault: stringPtr("not_this"), - hardDefault: stringPtr("not_this")}, + root: test.StringPtr("this"), + dfault: test.StringPtr("not_this"), + hardDefault: test.StringPtr("not_this")}, "default overrides hardDefault": { wantString: "this", - dfault: stringPtr("this"), - hardDefault: stringPtr("not_this")}, + dfault: test.StringPtr("this"), + hardDefault: test.StringPtr("not_this")}, "hardDefault is last resort": { wantString: "this", - hardDefault: stringPtr("this")}, + hardDefault: test.StringPtr("this")}, "env var is used": { wantString: "this", env: map[string]string{"TESTLOOKUP_LV_GETACCESSTOKEN_ONE": "this"}, - root: stringPtr("${TESTLOOKUP_LV_GETACCESSTOKEN_ONE}"), + root: test.StringPtr("${TESTLOOKUP_LV_GETACCESSTOKEN_ONE}"), }, "env var partial is used": { wantString: "this", env: map[string]string{"TESTLOOKUP_LV_GETACCESSTOKEN_TWO": "th"}, - root: stringPtr("${TESTLOOKUP_LV_GETACCESSTOKEN_TWO}is"), + root: test.StringPtr("${TESTLOOKUP_LV_GETACCESSTOKEN_TWO}is"), }, "empty env var is used": { wantString: "this", env: map[string]string{"TESTLOOKUP_LV_GETACCESSTOKEN_THREE": ""}, - root: stringPtr("th${TESTLOOKUP_LV_GETACCESSTOKEN_THREE}is"), + root: test.StringPtr("th${TESTLOOKUP_LV_GETACCESSTOKEN_THREE}is"), }, "undefined env var is used": { wantString: "${TESTLOOKUP_LV_GETACCESSTOKEN_UNSET}", - root: stringPtr("${TESTLOOKUP_LV_GETACCESSTOKEN_UNSET}"), - dfault: stringPtr("this"), + root: test.StringPtr("${TESTLOOKUP_LV_GETACCESSTOKEN_UNSET}"), + dfault: test.StringPtr("this"), }, } @@ -104,16 +105,16 @@ func TestLookup_GetAllowInvalidCerts(t *testing.T) { }{ "root overrides all": { wantBool: true, - root: boolPtr(true), - dfault: boolPtr(false), - hardDefault: boolPtr(false)}, + root: test.BoolPtr(true), + dfault: test.BoolPtr(false), + hardDefault: test.BoolPtr(false)}, "default overrides hardDefault": { wantBool: true, - dfault: boolPtr(true), - hardDefault: boolPtr(false)}, + dfault: test.BoolPtr(true), + hardDefault: test.BoolPtr(false)}, "hardDefault is last resort": { wantBool: true, - hardDefault: boolPtr(true)}, + hardDefault: test.BoolPtr(true)}, } for name, tc := range tests { @@ -216,7 +217,7 @@ func TestLookup_ServiceURL(t *testing.T) { status.Init( 0, 0, 0, &name, - stringPtr("http://example.com")) + test.StringPtr("http://example.com")) status.SetLatestVersion(tc.latestVersion, false) status.WebURL = &tc.webURL lookup := Lookup{Type: tc.serviceType, URL: tc.url, Status: &status} @@ -243,16 +244,16 @@ func TestLookup_GetUsePreRelease(t *testing.T) { }{ "root overrides all": { wantBool: true, - root: boolPtr(true), - dfault: boolPtr(false), - hardDefault: boolPtr(false)}, + root: test.BoolPtr(true), + dfault: test.BoolPtr(false), + hardDefault: test.BoolPtr(false)}, "default overrides hardDefault": { wantBool: true, - dfault: boolPtr(true), - hardDefault: boolPtr(false)}, + dfault: test.BoolPtr(true), + hardDefault: test.BoolPtr(false)}, "hardDefault is last resort": { wantBool: true, - hardDefault: boolPtr(true)}, + hardDefault: test.BoolPtr(true)}, } for name, tc := range tests { diff --git a/service/latest_version/help_test.go b/service/latest_version/help_test.go index cf5d6501..e0963724 100644 --- a/service/latest_version/help_test.go +++ b/service/latest_version/help_test.go @@ -18,23 +18,16 @@ package latestver import ( "os" - "strings" "testing" dbtype "github.com/release-argus/Argus/db/types" "github.com/release-argus/Argus/service/latest_version/filter" opt "github.com/release-argus/Argus/service/options" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) -func boolPtr(val bool) *bool { - return &val -} -func stringPtr(val string) *string { - return &val -} - // Unsure why Go tests give a different result than the compiled binary var initialEmptyListETag string @@ -61,14 +54,14 @@ func testLookup(urlType bool, allowInvalidCerts bool) *Lookup { &announceChannel, &databaseChannel, &saveChannel, "", "", "", "", "", "") lookup := New( - stringPtr(os.Getenv("GITHUB_TOKEN")), - boolPtr(allowInvalidCerts), + test.StringPtr(os.Getenv("GITHUB_TOKEN")), + test.BoolPtr(allowInvalidCerts), nil, opt.New( - nil, "", boolPtr(true), + nil, "", test.BoolPtr(true), &opt.OptionsDefaults{}, opt.NewDefaults( - "0s", boolPtr(true))), + "0s", test.BoolPtr(true))), &filter.Require{}, nil, "github", "release-argus/Argus", @@ -81,29 +74,21 @@ func testLookup(urlType bool, allowInvalidCerts bool) *Lookup { lookup.Type = "url" lookup.URL = "https://invalid.release-argus.io/plain" lookup.URLCommands = filter.URLCommandSlice{ - {Type: "regex", Regex: stringPtr("v([0-9.]+)")}} + {Type: "regex", Regex: test.StringPtr("v([0-9.]+)")}} } else { lookup.GitHubData = NewGitHubData("", nil) lookup.URLCommands = filter.URLCommandSlice{ - {Type: "regex", Regex: stringPtr("([0-9.]+)")}} - lookup.AccessToken = stringPtr(os.Getenv("GITHUB_TOKEN")) - lookup.UsePreRelease = boolPtr(false) + {Type: "regex", Regex: test.StringPtr("([0-9.]+)")}} + lookup.AccessToken = test.StringPtr(os.Getenv("GITHUB_TOKEN")) + lookup.UsePreRelease = test.BoolPtr(false) } lookup.Status.Init( 0, 0, 0, - stringPtr("serviceID"), - stringPtr("http://example.com"), + test.StringPtr("serviceID"), + test.StringPtr("http://example.com"), ) lookup.Require.Status = lookup.Status lookup.Defaults = &LookupDefaults{} lookup.HardDefaults = &LookupDefaults{} return lookup } - -func trimJSON(str string) string { - str = strings.TrimSpace(str) - str = strings.ReplaceAll(str, "\n", "") - str = strings.ReplaceAll(str, "\t", "") - str = strings.ReplaceAll(str, ": ", ":") - return str -} diff --git a/service/latest_version/init_test.go b/service/latest_version/init_test.go index bae581ed..694d8664 100644 --- a/service/latest_version/init_test.go +++ b/service/latest_version/init_test.go @@ -22,6 +22,7 @@ import ( "github.com/prometheus/client_golang/prometheus/testutil" opt "github.com/release-argus/Argus/service/options" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" metric "github.com/release-argus/Argus/web/metrics" ) @@ -81,7 +82,7 @@ func TestLookup_Init(t *testing.T) { var defaults LookupDefaults var hardDefaults LookupDefaults *lookup.Status.ServiceID += "TestInit" - status := svcstatus.Status{ServiceID: stringPtr("test")} + status := svcstatus.Status{ServiceID: test.StringPtr("test")} var options opt.Options // WHEN Init is called on it diff --git a/service/latest_version/query_test.go b/service/latest_version/query_test.go index 3b5d2f00..57a2b1c0 100644 --- a/service/latest_version/query_test.go +++ b/service/latest_version/query_test.go @@ -102,17 +102,17 @@ func TestLookup_Query(t *testing.T) { }, "query that gets a non-semantic version": { url: "https://valid.release-argus.io/plain", - regex: stringPtr(`"v[0-9.]+`), + regex: test.StringPtr(`"v[0-9.]+`), errRegex: "failed converting .* to a semantic version", }, "query on self-signed https works when allowed": { url: "https://invalid.release-argus.io/plain", - regex: stringPtr("v[0-9.]+"), + regex: test.StringPtr("v[0-9.]+"), allowInvalidCerts: true, }, "query on self-signed https fails when not allowed": { url: "https://invalid.release-argus.io/plain", - regex: stringPtr("v[0-9.]+"), + regex: test.StringPtr("v[0-9.]+"), allowInvalidCerts: false, errRegex: "x509", }, @@ -158,33 +158,33 @@ func TestLookup_Query(t *testing.T) { errRegex: "regex not matched on version", }, "urlCommand regex mismatch": { - regex: stringPtr("^[0-9]+$"), + regex: test.StringPtr("^[0-9]+$"), errRegex: "regex .* didn't return any matches", }, "valid semantic version query": { - regex: stringPtr("v([0-9.]+)"), + regex: test.StringPtr("v([0-9.]+)"), }, "older version found": { - regex: stringPtr("([0-9.]+)"), + regex: test.StringPtr("([0-9.]+)"), latestVersion: "0.0.0", deployedVersion: "9.9.9", errRegex: "queried version .* is less than the deployed version", }, "newer version found": { - regex: stringPtr("([0-9.]+)"), + regex: test.StringPtr("([0-9.]+)"), deployedVersion: "0.0.0", }, "same version found": { - regex: stringPtr("([0-9.]+)"), + regex: test.StringPtr("([0-9.]+)"), deployedVersion: "1.2.1", }, "no deployed version lookup": { - regex: stringPtr("([0-9.]+)-beta"), - wantLatestVersion: stringPtr("1.2.2"), + regex: test.StringPtr("([0-9.]+)-beta"), + wantLatestVersion: test.StringPtr("1.2.2"), }, "non-semantic version lookup": { - regex: stringPtr("v[0-9.]+"), - wantLatestVersion: stringPtr("v1.2.2"), + regex: test.StringPtr("v[0-9.]+"), + wantLatestVersion: test.StringPtr("v1.2.2"), nonSemanticVersioning: true, }, "github lookup": { @@ -193,7 +193,7 @@ func TestLookup_Query(t *testing.T) { "github lookup on repo that uses tags, not releases": { githubService: true, url: "go-vikunja/api", - regex: stringPtr("v([0-9.]+)"), + regex: test.StringPtr("v([0-9.]+)"), stdoutRegex: `no tags found on /releases, trying /tags`, }, "github lookup with no access token": { @@ -202,12 +202,12 @@ func TestLookup_Query(t *testing.T) { }, "github lookup with failing urlCommand match": { githubService: true, - regex: stringPtr("x([0-9.]+)"), + regex: test.StringPtr("x([0-9.]+)"), errRegex: "no releases were found matching the url_commands", }, "url_command makes all versions non-semmantic": { githubService: true, - regex: stringPtr(`([0-9.]+\.)`), + regex: test.StringPtr(`([0-9.]+\.)`), errRegex: "no releases were found matching the url_commands", }, } @@ -304,7 +304,7 @@ func TestLookup_Query__EmptyListETagChanged(t *testing.T) { temporaryFailureInNameResolution = false lookup := testLookup(false, false) lookup.URL = "go-vikunja/api" - lookup.URLCommands[0].Regex = stringPtr("v([0-9.]+)") + lookup.URLCommands[0].Regex = test.StringPtr("v([0-9.]+)") // WHEN Query is called on it _, err := lookup.Query(true, &util.LogFrom{}) @@ -364,7 +364,7 @@ func TestLookup_QueryGitHubETag(t *testing.T) { eTagChanged: 1, eTagUnchangedUseCache: 1, urlCommands: filter.URLCommandSlice{ - {Type: "regex", Regex: stringPtr(`^FOO$`)}}, + {Type: "regex", Regex: test.StringPtr(`^FOO$`)}}, errRegex: `no releases were found matching the url_commands no releases were found matching the url_commands and/or require`}, } diff --git a/service/latest_version/refresh_test.go b/service/latest_version/refresh_test.go index 1ed839d5..e5be7867 100644 --- a/service/latest_version/refresh_test.go +++ b/service/latest_version/refresh_test.go @@ -27,11 +27,12 @@ import ( "github.com/release-argus/Argus/service/latest_version/filter" opt "github.com/release-argus/Argus/service/options" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) func TestLookup_ApplyOverrides(t *testing.T) { - test := testLookup(true, true) + testL := testLookup(true, true) // GIVEN various json strings to parse as parts of a Lookup tests := map[string]struct { accessToken *string @@ -53,51 +54,51 @@ func TestLookup_ApplyOverrides(t *testing.T) { want: testLookup(true, true), }, "access token": { - accessToken: stringPtr("foo"), + accessToken: test.StringPtr("foo"), previous: testLookup(true, true), want: New( - stringPtr("foo"), - test.AllowInvalidCerts, + test.StringPtr("foo"), + testL.AllowInvalidCerts, nil, - test.Options, - test.Require, + testL.Options, + testL.Require, nil, - test.Type, - test.URL, - &test.URLCommands, - test.UsePreRelease, + testL.Type, + testL.URL, + &testL.URLCommands, + testL.UsePreRelease, &LookupDefaults{}, &LookupDefaults{}), }, "allow invalid certs": { - allowInvalidCerts: stringPtr("false"), + allowInvalidCerts: test.StringPtr("false"), previous: testLookup(true, true), want: New( - test.AccessToken, - boolPtr(false), + testL.AccessToken, + test.BoolPtr(false), nil, - test.Options, - test.Require, + testL.Options, + testL.Require, nil, - test.Type, - test.URL, - &test.URLCommands, - test.UsePreRelease, + testL.Type, + testL.URL, + &testL.URLCommands, + testL.UsePreRelease, &LookupDefaults{}, &LookupDefaults{}), }, "require": { - require: stringPtr(`{ + require: test.StringPtr(`{ "docker": { "type": "ghcr", "image": "release-argus/Argus", "tag": "latest"}}`), previous: testLookup(true, true), want: New( - test.AccessToken, - test.AllowInvalidCerts, + testL.AccessToken, + testL.AllowInvalidCerts, nil, - test.Options, + testL.Options, &filter.Require{ Docker: filter.NewDockerCheck( "ghcr", @@ -105,15 +106,15 @@ func TestLookup_ApplyOverrides(t *testing.T) { "latest", "", "", "", time.Now(), nil)}, nil, - test.Type, - test.URL, - &test.URLCommands, - test.UsePreRelease, + testL.Type, + testL.URL, + &testL.URLCommands, + testL.UsePreRelease, &LookupDefaults{}, &LookupDefaults{}), }, "require - no docker.type fail": { - require: stringPtr(`{ + require: test.StringPtr(`{ "docker": { "type": "", "image": "release-argus/Argus", @@ -122,7 +123,7 @@ func TestLookup_ApplyOverrides(t *testing.T) { errRegex: `^require:[^ ]+ docker:[^ ]+ type: `, }, "require - invalid": { - require: stringPtr(`{ + require: test.StringPtr(`{ "docker": { "type": "foo", "image": "release-argus/Argus", @@ -131,109 +132,109 @@ func TestLookup_ApplyOverrides(t *testing.T) { errRegex: `type: ".*" `, }, "semantic versioning": { - semanticVersioning: stringPtr("false"), + semanticVersioning: test.StringPtr("false"), previous: testLookup(true, true), want: New( - test.AccessToken, - test.AllowInvalidCerts, + testL.AccessToken, + testL.AllowInvalidCerts, nil, opt.New( - nil, "", boolPtr(false), + nil, "", test.BoolPtr(false), nil, nil), - test.Require, + testL.Require, nil, - test.Type, - test.URL, - &test.URLCommands, - test.UsePreRelease, + testL.Type, + testL.URL, + &testL.URLCommands, + testL.UsePreRelease, &LookupDefaults{}, &LookupDefaults{}), }, "url": { - url: stringPtr("https://valid.release-argus.io/json"), + url: test.StringPtr("https://valid.release-argus.io/json"), previous: testLookup(true, true), want: New( - test.AccessToken, - test.AllowInvalidCerts, + testL.AccessToken, + testL.AllowInvalidCerts, nil, - test.Options, - test.Require, + testL.Options, + testL.Require, nil, - test.Type, + testL.Type, "https://valid.release-argus.io/json", - &test.URLCommands, - test.UsePreRelease, + &testL.URLCommands, + testL.UsePreRelease, &LookupDefaults{}, &LookupDefaults{}), }, "url commands": { - urlCommands: stringPtr(`[ + urlCommands: test.StringPtr(`[ {"type": "regex", "regex": "v?([0-9.]})"} ]`), previous: testLookup(true, true), want: New( - test.AccessToken, - test.AllowInvalidCerts, + testL.AccessToken, + testL.AllowInvalidCerts, nil, - test.Options, - test.Require, + testL.Options, + testL.Require, nil, - test.Type, - test.URL, + testL.Type, + testL.URL, &filter.URLCommandSlice{ - {Type: "regex", Regex: stringPtr("v?([0-9.]})")}}, - test.UsePreRelease, + {Type: "regex", Regex: test.StringPtr("v?([0-9.]})")}}, + testL.UsePreRelease, &LookupDefaults{}, &LookupDefaults{}), }, "url commands - invalid": { - urlCommands: stringPtr(`[ + urlCommands: test.StringPtr(`[ {"type": "foo", "regex": "v?([0-9.]})"}]`), previous: testLookup(true, true), want: nil, errRegex: `type: .* `, }, "use prerelease": { - usePreRelease: stringPtr("true"), + usePreRelease: test.StringPtr("true"), previous: testLookup(true, true), want: New( - test.AccessToken, - test.AllowInvalidCerts, + testL.AccessToken, + testL.AllowInvalidCerts, nil, - test.Options, - test.Require, + testL.Options, + testL.Require, nil, - test.Type, - test.URL, - &test.URLCommands, - boolPtr(true), + testL.Type, + testL.URL, + &testL.URLCommands, + test.BoolPtr(true), &LookupDefaults{}, &LookupDefaults{}), }, "type github defaulted if not set": { - url: stringPtr("release-argus/Argus"), + url: test.StringPtr("release-argus/Argus"), previous: &Lookup{ Options: &opt.Options{}, Status: &svcstatus.Status{ - ServiceID: stringPtr("test")}}, + ServiceID: test.StringPtr("test")}}, want: &Lookup{ Type: "github", URL: "release-argus/Argus", GitHubData: NewGitHubData("", nil)}, }, "type github carries over Releases and ETag": { - url: stringPtr("release-argus/other"), + url: test.StringPtr("release-argus/other"), previous: New( - test.AccessToken, - test.AllowInvalidCerts, + testL.AccessToken, + testL.AllowInvalidCerts, nil, - test.Options, - test.Require, + testL.Options, + testL.Require, nil, "github", "release-argus/Argus", nil, - boolPtr(false), + test.BoolPtr(false), &LookupDefaults{}, &LookupDefaults{}), carryOverGitHubData: true, @@ -242,33 +243,33 @@ func TestLookup_ApplyOverrides(t *testing.T) { releases: []github_types.Release{ {TagName: "v1.0.0"}}}, want: New( - test.AccessToken, - test.AllowInvalidCerts, + testL.AccessToken, + testL.AllowInvalidCerts, nil, - test.Options, - test.Require, + testL.Options, + testL.Require, nil, "github", "release-argus/other", nil, - boolPtr(false), + test.BoolPtr(false), &LookupDefaults{}, &LookupDefaults{}), }, "GitHubData removed if type changed from github": { - url: stringPtr("https://valid.release-argus.io/json"), - typeStr: stringPtr("url"), + url: test.StringPtr("https://valid.release-argus.io/json"), + typeStr: test.StringPtr("url"), previous: New( - test.AccessToken, - test.AllowInvalidCerts, + testL.AccessToken, + testL.AllowInvalidCerts, nil, - test.Options, - test.Require, + testL.Options, + testL.Require, nil, "github", "release-argus/Argus", nil, - boolPtr(false), + test.BoolPtr(false), &LookupDefaults{}, &LookupDefaults{}), carryOverGitHubData: false, @@ -277,21 +278,21 @@ func TestLookup_ApplyOverrides(t *testing.T) { releases: []github_types.Release{ {TagName: "v1.0.0"}}}, want: New( - test.AccessToken, - test.AllowInvalidCerts, + testL.AccessToken, + testL.AllowInvalidCerts, nil, - test.Options, - test.Require, + testL.Options, + testL.Require, nil, "url", "https://valid.release-argus.io/json", nil, - boolPtr(false), + test.BoolPtr(false), &LookupDefaults{}, &LookupDefaults{}), }, "override with invalid (empty) url": { - url: stringPtr(""), + url: test.StringPtr(""), previous: testLookup(true, true), want: nil, errRegex: "url: ", @@ -355,7 +356,7 @@ func TestLookup_Refresh(t *testing.T) { testURL.Query(true, &util.LogFrom{}) testVersionURL := testURL.Status.LatestVersion() testGitHub := testLookup(false, false) - testGitHub.AccessToken = stringPtr(os.Getenv("GITHUB_TOKEN")) + testGitHub.AccessToken = test.StringPtr(os.Getenv("GITHUB_TOKEN")) testGitHub.Query(true, &util.LogFrom{}) testVersionGitHub := testGitHub.Status.LatestVersion() @@ -376,25 +377,25 @@ func TestLookup_Refresh(t *testing.T) { announce bool }{ "Change of URL": { - url: stringPtr("https://valid.release-argus.io/plain"), + url: test.StringPtr("https://valid.release-argus.io/plain"), previous: testLookup(true, true), want: testVersionURL, }, "Removal of URL": { - url: stringPtr(""), + url: test.StringPtr(""), previous: testLookup(true, true), errRegex: "url: ", want: "", }, "Change of a few vars": { - urlCommands: stringPtr(`[ + urlCommands: test.StringPtr(`[ {"type": "regex", "regex": "beta: \"v?([^\"]+)"}]`), - semanticVersioning: stringPtr("false"), + semanticVersioning: test.StringPtr("false"), previous: testLookup(true, true), want: testVersionURL + "-beta", }, "Change of vars that fail Query": { - allowInvalidCerts: stringPtr("false"), + allowInvalidCerts: test.StringPtr("false"), previous: testLookup(true, true), errRegex: `x509 \(certificate invalid\)`, }, @@ -439,7 +440,7 @@ func TestLookup_Refresh(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - tc.previous.AccessToken = stringPtr(os.Getenv("GITHUB_TOKEN")) + tc.previous.AccessToken = test.StringPtr(os.Getenv("GITHUB_TOKEN")) // Copy the starting status tc.previous.Status.Init( 0, 0, 0, diff --git a/service/latest_version/types_test.go b/service/latest_version/types_test.go index ed44e3d8..54f11216 100644 --- a/service/latest_version/types_test.go +++ b/service/latest_version/types_test.go @@ -26,6 +26,7 @@ import ( "github.com/release-argus/Argus/service/latest_version/filter" opt "github.com/release-argus/Argus/service/options" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" ) var emptyListETagTestMutex = sync.Mutex{} @@ -292,8 +293,8 @@ func TestLookup_String(t *testing.T) { }, "filled": { lookup: New( - stringPtr("token"), - boolPtr(true), + test.StringPtr("token"), + test.BoolPtr(true), nil, opt.New( nil, "1h2m3s", nil, @@ -305,12 +306,12 @@ func TestLookup_String(t *testing.T) { "github", "https://test.com", &filter.URLCommandSlice{ - {Type: "regex", Regex: stringPtr("v([0-9.]+)")}}, - boolPtr(true), + {Type: "regex", Regex: test.StringPtr("v([0-9.]+)")}}, + test.BoolPtr(true), NewDefaults( - stringPtr("foo"), nil, nil, nil), + test.StringPtr("foo"), nil, nil, nil), NewDefaults( - nil, boolPtr(true), nil, nil)), + nil, test.BoolPtr(true), nil, nil)), want: ` type: github url: https://test.com @@ -326,10 +327,10 @@ require: }, "quotes otherwise invalid yaml strings": { lookup: New( - stringPtr(">123"), + test.StringPtr(">123"), nil, nil, nil, nil, nil, "", "", &filter.URLCommandSlice{ - {Type: "regex", Regex: stringPtr("{2}([0-9.]+)")}}, + {Type: "regex", Regex: test.StringPtr("{2}([0-9.]+)")}}, nil, nil, nil), want: ` access_token: '>123' @@ -390,7 +391,7 @@ func TestGitHubData_String(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - tc.want = trimJSON(tc.want) + tc.want = test.TrimJSON(tc.want) // WHEN the GitHubData is stringified with String got := tc.githubData.String() @@ -418,24 +419,24 @@ func TestLookup_IsEqual(t *testing.T) { "defaults ignored": { a: &Lookup{ Defaults: NewDefaults( - nil, boolPtr(false), nil, nil)}, + nil, test.BoolPtr(false), nil, nil)}, b: &Lookup{}, want: true, }, "hard_defaults ignored": { a: &Lookup{ HardDefaults: NewDefaults( - nil, boolPtr(false), nil, nil)}, + nil, test.BoolPtr(false), nil, nil)}, b: &Lookup{}, want: true, }, "equal": { a: New( - stringPtr("token"), - boolPtr(false), + test.StringPtr("token"), + test.BoolPtr(false), nil, opt.New( - nil, "", boolPtr(true), + nil, "", test.BoolPtr(true), nil, nil), &filter.Require{ RegexContent: "foo.tar.gz"}, @@ -444,15 +445,15 @@ func TestLookup_IsEqual(t *testing.T) { "https://example.com", nil, nil, NewDefaults( - stringPtr("foo"), nil, nil, nil), + test.StringPtr("foo"), nil, nil, nil), NewDefaults( - nil, boolPtr(true), nil, nil)), + nil, test.BoolPtr(true), nil, nil)), b: New( - stringPtr("token"), - boolPtr(false), + test.StringPtr("token"), + test.BoolPtr(false), nil, opt.New( - nil, "", boolPtr(true), + nil, "", test.BoolPtr(true), nil, nil), &filter.Require{ RegexContent: "foo.tar.gz"}, @@ -461,18 +462,18 @@ func TestLookup_IsEqual(t *testing.T) { "https://example.com", nil, nil, NewDefaults( - stringPtr("foo"), nil, nil, nil), + test.StringPtr("foo"), nil, nil, nil), NewDefaults( - nil, boolPtr(true), nil, nil)), + nil, test.BoolPtr(true), nil, nil)), want: true, }, "not equal": { a: New( - stringPtr("token"), - boolPtr(false), + test.StringPtr("token"), + test.BoolPtr(false), nil, opt.New( - nil, "", boolPtr(true), + nil, "", test.BoolPtr(true), nil, nil), &filter.Require{ RegexContent: "foo.tar.gz"}, @@ -480,17 +481,17 @@ func TestLookup_IsEqual(t *testing.T) { "github", "https://example.com", nil, - boolPtr(true), + test.BoolPtr(true), NewDefaults( - stringPtr("foo"), nil, nil, nil), + test.StringPtr("foo"), nil, nil, nil), NewDefaults( - nil, boolPtr(true), nil, nil)), + nil, test.BoolPtr(true), nil, nil)), b: New( - stringPtr("token"), - boolPtr(false), + test.StringPtr("token"), + test.BoolPtr(false), nil, opt.New( - nil, "", boolPtr(true), + nil, "", test.BoolPtr(true), nil, nil), &filter.Require{ RegexContent: "foo.tar.gz"}, @@ -498,11 +499,11 @@ func TestLookup_IsEqual(t *testing.T) { "github", "https://example.com/other", nil, - boolPtr(true), + test.BoolPtr(true), NewDefaults( - stringPtr("foo"), nil, nil, nil), + test.StringPtr("foo"), nil, nil, nil), NewDefaults( - nil, boolPtr(true), nil, nil)), + nil, test.BoolPtr(true), nil, nil)), want: false, }, "not equal with nil": { @@ -523,7 +524,7 @@ func TestLookup_IsEqual(t *testing.T) { tc.a.Status.Init( 0, 0, 0, &name, - stringPtr("http://example.com")) + test.StringPtr("http://example.com")) tc.a.Status.SetLatestVersion("foo", false) } diff --git a/service/latest_version/verify_test.go b/service/latest_version/verify_test.go index 879efb79..8b5ba0b3 100644 --- a/service/latest_version/verify_test.go +++ b/service/latest_version/verify_test.go @@ -22,6 +22,7 @@ import ( "testing" "github.com/release-argus/Argus/service/latest_version/filter" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) @@ -95,24 +96,24 @@ func TestLookup_CheckValues(t *testing.T) { errRegex: []string{ `^latest_version:$`, `^ type: `}, - lType: stringPtr(""), + lType: test.StringPtr(""), }, "invalid type": { errRegex: []string{ `^latest_version:$`, `^ type: "[^"]+" `}, - lType: stringPtr("foo"), + lType: test.StringPtr("foo"), }, "no url": { errRegex: []string{ `^latest_version:$`, `^ url: `}, - url: stringPtr(""), + url: test.StringPtr(""), }, "corrects github url": { errRegex: []string{}, - url: stringPtr("https://github.com/release-argus/Argus"), - wantURL: stringPtr("release-argus/Argus"), + url: test.StringPtr("https://github.com/release-argus/Argus"), + wantURL: test.StringPtr("release-argus/Argus"), }, "invalid require": { errRegex: []string{ @@ -138,7 +139,7 @@ func TestLookup_CheckValues(t *testing.T) { `^ url_commands:$`, `^ item_0:$`, `^ type: "[^"]+" `}, - url: stringPtr(""), + url: test.StringPtr(""), require: &filter.Require{RegexContent: "[0-"}, urlCommands: &filter.URLCommandSlice{{Type: "foo"}}, }, diff --git a/service/new_test.go b/service/new_test.go index b4490a54..7b3f897c 100644 --- a/service/new_test.go +++ b/service/new_test.go @@ -32,6 +32,7 @@ import ( "github.com/release-argus/Argus/service/latest_version/filter" opt "github.com/release-argus/Argus/service/options" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" "github.com/release-argus/Argus/webhook" ) @@ -48,35 +49,35 @@ func TestService_GiveSecretsLatestVersion(t *testing.T) { "empty AccessToken": { latestVersion: &latestver.Lookup{}, otherLV: latestver.New( - stringPtr("foo"), + test.StringPtr("foo"), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), expected: &latestver.Lookup{}, }, "new AccessToken kept": { latestVersion: latestver.New( - stringPtr("foo"), + test.StringPtr("foo"), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), otherLV: latestver.New( - stringPtr("bar"), + test.StringPtr("bar"), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), expected: latestver.New( - stringPtr("foo"), + test.StringPtr("foo"), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), }, "give old AccessToken": { latestVersion: latestver.New( - stringPtr(""), + test.StringPtr(""), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), otherLV: latestver.New( - stringPtr("bar"), + test.StringPtr("bar"), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), expected: latestver.New( - stringPtr("bar"), + test.StringPtr("bar"), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), }, "referncing default AccessToken": { latestVersion: latestver.New( - stringPtr(""), + test.StringPtr(""), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), otherLV: latestver.New( nil, @@ -352,8 +353,8 @@ func TestService_GiveSecretsDeployedVersion(t *testing.T) { {Key: "bash", Value: ""}}}, secretRefs: dvSecretRef{ Headers: []oldIntIndex{ - {OldIndex: intPtr(0)}, - {OldIndex: intPtr(1)}}}, + {OldIndex: test.IntPtr(0)}, + {OldIndex: test.IntPtr(1)}}}, }, "Headers with but nil index refs": { deployedVersion: &deployedver.Lookup{ @@ -385,7 +386,7 @@ func TestService_GiveSecretsDeployedVersion(t *testing.T) { {Key: "foo", Value: "shazam"}}}, secretRefs: dvSecretRef{ Headers: []oldIntIndex{ - {OldIndex: intPtr(0)}}}, + {OldIndex: test.IntPtr(0)}}}, }, "only new/changed Headers": { deployedVersion: &deployedver.Lookup{ @@ -401,7 +402,7 @@ func TestService_GiveSecretsDeployedVersion(t *testing.T) { {Key: "bish", Value: "bash"}}}, secretRefs: dvSecretRef{ Headers: []oldIntIndex{ - {OldIndex: intPtr(0)}, {OldIndex: nil}}}, + {OldIndex: test.IntPtr(0)}, {OldIndex: nil}}}, }, "only new/changed Headers with expected refs": { deployedVersion: &deployedver.Lookup{ @@ -417,7 +418,7 @@ func TestService_GiveSecretsDeployedVersion(t *testing.T) { {Key: "bish", Value: "bash"}}}, secretRefs: dvSecretRef{ Headers: []oldIntIndex{ - {OldIndex: intPtr(0)}, {OldIndex: nil}}}, + {OldIndex: test.IntPtr(0)}, {OldIndex: nil}}}, }, "only new/changed Headers with no refs": { deployedVersion: &deployedver.Lookup{ @@ -466,7 +467,7 @@ func TestService_GiveSecretsDeployedVersion(t *testing.T) { {Key: "bosh", Value: ""}}}, secretRefs: dvSecretRef{ Headers: []oldIntIndex{ - {OldIndex: intPtr(0)}, {OldIndex: intPtr(1)}}}, + {OldIndex: test.IntPtr(0)}, {OldIndex: test.IntPtr(1)}}}, }, "referencing old Header value": { deployedVersion: &deployedver.Lookup{ @@ -482,7 +483,7 @@ func TestService_GiveSecretsDeployedVersion(t *testing.T) { {Key: "bish", Value: "bash"}}}, secretRefs: dvSecretRef{ Headers: []oldIntIndex{ - {OldIndex: intPtr(0)}, {OldIndex: nil}}}, + {OldIndex: test.IntPtr(0)}, {OldIndex: nil}}}, }, "referencing old Header value that doesn't exist": { deployedVersion: &deployedver.Lookup{ @@ -498,7 +499,7 @@ func TestService_GiveSecretsDeployedVersion(t *testing.T) { {Key: "bish", Value: "bash"}}}, secretRefs: dvSecretRef{ Headers: []oldIntIndex{ - {OldIndex: intPtr(1)}, {OldIndex: nil}}}, + {OldIndex: test.IntPtr(1)}, {OldIndex: nil}}}, }, "referencing some old Header values but not others": { deployedVersion: &deployedver.Lookup{ @@ -515,7 +516,7 @@ func TestService_GiveSecretsDeployedVersion(t *testing.T) { {Key: "bish", Value: "bong"}}}, secretRefs: dvSecretRef{ Headers: []oldIntIndex{ - {OldIndex: nil}, {OldIndex: intPtr(1)}}}, + {OldIndex: nil}, {OldIndex: test.IntPtr(1)}}}, }, "swap header values": { deployedVersion: &deployedver.Lookup{ @@ -532,7 +533,7 @@ func TestService_GiveSecretsDeployedVersion(t *testing.T) { {Key: "foo", Value: "bong"}}}, secretRefs: dvSecretRef{ Headers: []oldIntIndex{ - {OldIndex: intPtr(0)}, {OldIndex: intPtr(1)}}}, + {OldIndex: test.IntPtr(0)}, {OldIndex: test.IntPtr(1)}}}, }, } @@ -678,7 +679,7 @@ func TestService_GiveSecretsNotify(t *testing.T) { &map[string]string{ "apikey": ""}, nil, nil, nil)}, - secretRefs: &map[string]oldStringIndex{"bish": {OldIndex: stringPtr("bash")}}, + secretRefs: &map[string]oldStringIndex{"bish": {OldIndex: test.StringPtr("bash")}}, }, "secretRef referencing nil index": { notify: shoutrrr.Slice{ @@ -740,7 +741,7 @@ func TestService_GiveSecretsNotify(t *testing.T) { &map[string]string{ "apikey": "yikes"}, nil, nil, nil)}, - secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: stringPtr("baz")}}, + secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: test.StringPtr("baz")}}, }, "secretRefs - url_fields.altid": { notify: shoutrrr.Slice{ @@ -771,7 +772,7 @@ func TestService_GiveSecretsNotify(t *testing.T) { &map[string]string{ "apikey": "yikes"}, nil, nil, nil)}, - secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: stringPtr("foo")}}, + secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: test.StringPtr("foo")}}, }, "secretRefs - url_fields.apikey": { notify: shoutrrr.Slice{ @@ -802,7 +803,7 @@ func TestService_GiveSecretsNotify(t *testing.T) { &map[string]string{ "apikey": "yikes"}, nil, nil, nil)}, - secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: stringPtr("foo")}}, + secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: test.StringPtr("foo")}}, }, "secretRefs - url_fields.apikey swap vars": { notify: shoutrrr.Slice{ @@ -839,8 +840,8 @@ func TestService_GiveSecretsNotify(t *testing.T) { "apikey": "something"}, nil, nil, nil)}, secretRefs: &map[string]oldStringIndex{ - "bar": {OldIndex: stringPtr("foo")}, - "foo": {OldIndex: stringPtr("bar")}}, + "bar": {OldIndex: test.StringPtr("foo")}, + "foo": {OldIndex: test.StringPtr("bar")}}, }, "secretRefs - url_fields.apikey swap vars ignores notify order": { notify: shoutrrr.Slice{ @@ -877,8 +878,8 @@ func TestService_GiveSecretsNotify(t *testing.T) { "apikey": "something"}, nil, nil, nil)}, secretRefs: &map[string]oldStringIndex{ - "bar": {OldIndex: stringPtr("foo")}, - "foo": {OldIndex: stringPtr("bar")}}, + "bar": {OldIndex: test.StringPtr("foo")}, + "foo": {OldIndex: test.StringPtr("bar")}}, }, "secretRefs - url_fields.botkey": { notify: shoutrrr.Slice{ @@ -909,7 +910,7 @@ func TestService_GiveSecretsNotify(t *testing.T) { &map[string]string{ "botkey": "yikes"}, nil, nil, nil)}, - secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: stringPtr("foo")}}, + secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: test.StringPtr("foo")}}, }, "secretRefs - url_fields.password": { notify: shoutrrr.Slice{ @@ -940,7 +941,7 @@ func TestService_GiveSecretsNotify(t *testing.T) { &map[string]string{ "password": "yikes"}, nil, nil, nil)}, - secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: stringPtr("foo")}}, + secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: test.StringPtr("foo")}}, }, "secretRefs - url_fields.token": { notify: shoutrrr.Slice{ @@ -971,7 +972,7 @@ func TestService_GiveSecretsNotify(t *testing.T) { &map[string]string{ "token": "yikes"}, nil, nil, nil)}, - secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: stringPtr("foo")}}, + secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: test.StringPtr("foo")}}, }, "secretRefs - url_fields.tokena": { notify: shoutrrr.Slice{ @@ -1002,7 +1003,7 @@ func TestService_GiveSecretsNotify(t *testing.T) { &map[string]string{ "tokena": "yikes"}, nil, nil, nil)}, - secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: stringPtr("foo")}}, + secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: test.StringPtr("foo")}}, }, "secretRefs - url_fields.tokenb": { notify: shoutrrr.Slice{ @@ -1033,7 +1034,7 @@ func TestService_GiveSecretsNotify(t *testing.T) { &map[string]string{ "tokenb": "yikes"}, nil, nil, nil)}, - secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: stringPtr("foo")}}, + secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: test.StringPtr("foo")}}, }, "secretRefs - url_fields.host ignored as ": { notify: shoutrrr.Slice{ @@ -1064,7 +1065,7 @@ func TestService_GiveSecretsNotify(t *testing.T) { &map[string]string{ "host": "https://example.com"}, nil, nil, nil)}, - secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: stringPtr("foo")}}, + secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: test.StringPtr("foo")}}, }, "secretRefs - params.devices": { notify: shoutrrr.Slice{ @@ -1095,7 +1096,7 @@ func TestService_GiveSecretsNotify(t *testing.T) { &map[string]string{ "devices": "yikes"}, "", nil, nil, nil, nil)}, - secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: stringPtr("foo")}}, + secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: test.StringPtr("foo")}}, }, "secretRefs - params.avatar ignored as ": { notify: shoutrrr.Slice{ @@ -1126,7 +1127,7 @@ func TestService_GiveSecretsNotify(t *testing.T) { &map[string]string{ "avatar": "https://example.com"}, "", nil, nil, nil, nil)}, - secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: stringPtr("foo")}}, + secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: test.StringPtr("foo")}}, }, "secretRefs - ALL": { notify: shoutrrr.Slice{ @@ -1174,7 +1175,7 @@ func TestService_GiveSecretsNotify(t *testing.T) { "tokena": "bosh", "tokenb": "bash"}, nil, nil, nil)}, - secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: stringPtr("foo")}}, + secretRefs: &map[string]oldStringIndex{"foo": {OldIndex: test.StringPtr("foo")}}, }, } @@ -1208,7 +1209,7 @@ func TestService_GiveSecretsNotify(t *testing.T) { func TestService_GiveSecretsWebHook(t *testing.T) { // GIVEN a WebHookSlice that may have secrets in it referencing those in another WebHookSliceSlice - test := map[string]struct { + tests := map[string]struct { webhook webhook.Slice otherWebhook *webhook.Slice expected webhook.Slice @@ -1291,7 +1292,7 @@ func TestService_GiveSecretsWebHook(t *testing.T) { "", nil, "", "", nil, nil, nil)}, secretRefs: &map[string]whSecretRef{ - "bish": {OldIndex: stringPtr("bash")}}, + "bish": {OldIndex: test.StringPtr("bash")}}, }, "secretRef referencing nil index": { webhook: webhook.Slice{ @@ -1346,7 +1347,7 @@ func TestService_GiveSecretsWebHook(t *testing.T) { "whoosh", nil, "", "", nil, nil, nil)}, secretRefs: &map[string]whSecretRef{ - "foo": {OldIndex: stringPtr("bash")}, + "foo": {OldIndex: test.StringPtr("bash")}, "bar": {OldIndex: nil}}, }, "secretRefs - secret": { @@ -1374,7 +1375,7 @@ func TestService_GiveSecretsWebHook(t *testing.T) { "whoosh", nil, "", "", nil, nil, nil)}, secretRefs: &map[string]whSecretRef{ - "foo": {OldIndex: stringPtr("foo")}, + "foo": {OldIndex: test.StringPtr("foo")}, "bar": {OldIndex: nil}}, }, "secretRefs - secret swap vars": { @@ -1406,8 +1407,8 @@ func TestService_GiveSecretsWebHook(t *testing.T) { "shazam", nil, "", "", nil, nil, nil)}, secretRefs: &map[string]whSecretRef{ - "bar": {OldIndex: stringPtr("foo")}, - "foo": {OldIndex: stringPtr("bar")}}, + "bar": {OldIndex: test.StringPtr("foo")}, + "foo": {OldIndex: test.StringPtr("bar")}}, }, "secretRefs - secret swap vars ignores order sent": { webhook: webhook.Slice{ @@ -1438,8 +1439,8 @@ func TestService_GiveSecretsWebHook(t *testing.T) { "shazam", nil, "", "", nil, nil, nil)}, secretRefs: &map[string]whSecretRef{ - "bar": {OldIndex: stringPtr("foo")}, - "foo": {OldIndex: stringPtr("bar")}}, + "bar": {OldIndex: test.StringPtr("foo")}, + "foo": {OldIndex: test.StringPtr("bar")}}, }, "custom headers - no secretRefs": { webhook: webhook.Slice{ @@ -1515,8 +1516,8 @@ func TestService_GiveSecretsWebHook(t *testing.T) { "", nil, nil, nil, nil, nil, "", nil, "", "", nil, nil, nil), }, secretRefs: &map[string]whSecretRef{ - "foo": {OldIndex: stringPtr("foo")}, - "bar": {OldIndex: stringPtr("bar")}, + "foo": {OldIndex: test.StringPtr("foo")}, + "bar": {OldIndex: test.StringPtr("bar")}, }, }, "custom headers - header secretRefs but old secrets unwanted": { @@ -1558,13 +1559,13 @@ func TestService_GiveSecretsWebHook(t *testing.T) { }, secretRefs: &map[string]whSecretRef{ "foo": { - OldIndex: stringPtr("foo"), + OldIndex: test.StringPtr("foo"), CustomHeaders: []oldIntIndex{ - {OldIndex: intPtr(0)}}}, + {OldIndex: test.IntPtr(0)}}}, "bar": { - OldIndex: stringPtr("bar"), + OldIndex: test.StringPtr("bar"), CustomHeaders: []oldIntIndex{ - {OldIndex: intPtr(0)}}}, + {OldIndex: test.IntPtr(0)}}}, }, }, "custom headers - header secretRefs, some indices out of range": { @@ -1610,13 +1611,13 @@ func TestService_GiveSecretsWebHook(t *testing.T) { "", nil, nil, nil, nil, nil, "", nil, "", "", nil, nil, nil)}, secretRefs: &map[string]whSecretRef{ "foo": { - OldIndex: stringPtr("foo"), + OldIndex: test.StringPtr("foo"), CustomHeaders: []oldIntIndex{ - {OldIndex: intPtr(5)}, {OldIndex: intPtr(1)}}}, + {OldIndex: test.IntPtr(5)}, {OldIndex: test.IntPtr(1)}}}, "bar": { - OldIndex: stringPtr("bar"), + OldIndex: test.StringPtr("bar"), CustomHeaders: []oldIntIndex{ - {OldIndex: intPtr(0)}, {OldIndex: intPtr(2)}}}, + {OldIndex: test.IntPtr(0)}, {OldIndex: test.IntPtr(2)}}}, }, }, "custom headers - header secretRefs use all secrets": { @@ -1661,15 +1662,15 @@ func TestService_GiveSecretsWebHook(t *testing.T) { "", nil, nil, nil, nil, nil, "", nil, "", "", nil, nil, nil)}, secretRefs: &map[string]whSecretRef{ "foo": { - OldIndex: stringPtr("foo"), + OldIndex: test.StringPtr("foo"), CustomHeaders: []oldIntIndex{ - {OldIndex: intPtr(0)}, - {OldIndex: intPtr(1)}}}, + {OldIndex: test.IntPtr(0)}, + {OldIndex: test.IntPtr(1)}}}, "bar": { - OldIndex: stringPtr("bar"), + OldIndex: test.StringPtr("bar"), CustomHeaders: []oldIntIndex{ - {OldIndex: intPtr(0)}, - {OldIndex: intPtr(1)}}}}, + {OldIndex: test.IntPtr(0)}, + {OldIndex: test.IntPtr(1)}}}}, }, "custom headers - header secretRefs, swap names of webhook": { webhook: webhook.Slice{ @@ -1713,19 +1714,19 @@ func TestService_GiveSecretsWebHook(t *testing.T) { "", nil, nil, nil, nil, nil, "", nil, "", "", nil, nil, nil)}, secretRefs: &map[string]whSecretRef{ "bar": { - OldIndex: stringPtr("foo"), + OldIndex: test.StringPtr("foo"), CustomHeaders: []oldIntIndex{ - {OldIndex: intPtr(0)}, - {OldIndex: intPtr(1)}}}, + {OldIndex: test.IntPtr(0)}, + {OldIndex: test.IntPtr(1)}}}, "foo": { - OldIndex: stringPtr("bar"), + OldIndex: test.StringPtr("bar"), CustomHeaders: []oldIntIndex{ - {OldIndex: intPtr(0)}, - {OldIndex: intPtr(1)}}}}, + {OldIndex: test.IntPtr(0)}, + {OldIndex: test.IntPtr(1)}}}}, }, } - for name, tc := range test { + for name, tc := range tests { t.Run(name, func(t *testing.T) { t.Parallel() @@ -1747,13 +1748,13 @@ func TestService_GiveSecretsWebHook(t *testing.T) { otherServiceStatus := svcstatus.Status{} otherServiceStatus.Init( len(*tc.otherWebhook), 0, 0, - stringPtr("otherService"), + test.StringPtr("otherService"), nil) tc.otherWebhook.Init( &otherServiceStatus, &webhook.SliceDefaults{}, &webhook.WebHookDefaults{}, &webhook.WebHookDefaults{}, nil, - stringPtr("10m")) + test.StringPtr("10m")) } // WHEN we call giveSecretsWebHook @@ -1792,7 +1793,7 @@ func TestService_GiveSecrets(t *testing.T) { "no secrets": { svc: &Service{ LatestVersion: *latestver.New( - stringPtr("something"), + test.StringPtr("something"), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), DeployedVersionLookup: &deployedver.Lookup{ BasicAuth: &deployedver.BasicAuth{ @@ -1825,7 +1826,7 @@ func TestService_GiveSecrets(t *testing.T) { }, oldService: &Service{ LatestVersion: *latestver.New( - stringPtr("somethingelse"), + test.StringPtr("somethingelse"), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), DeployedVersionLookup: &deployedver.Lookup{ BasicAuth: &deployedver.BasicAuth{ @@ -1858,7 +1859,7 @@ func TestService_GiveSecrets(t *testing.T) { }, expected: &Service{ LatestVersion: *latestver.New( - stringPtr("something"), + test.StringPtr("something"), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), DeployedVersionLookup: &deployedver.Lookup{ BasicAuth: &deployedver.BasicAuth{ @@ -1900,7 +1901,7 @@ func TestService_GiveSecrets(t *testing.T) { "no oldService (CREATE)": { svc: &Service{ LatestVersion: *latestver.New( - stringPtr(""), + test.StringPtr(""), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), DeployedVersionLookup: &deployedver.Lookup{ BasicAuth: &deployedver.BasicAuth{ @@ -1935,7 +1936,7 @@ func TestService_GiveSecrets(t *testing.T) { oldService: nil, expected: &Service{ LatestVersion: *latestver.New( - stringPtr(""), + test.StringPtr(""), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), DeployedVersionLookup: &deployedver.Lookup{ BasicAuth: &deployedver.BasicAuth{ @@ -1972,7 +1973,7 @@ func TestService_GiveSecrets(t *testing.T) { "no secretRefs": { svc: &Service{ LatestVersion: *latestver.New( - stringPtr(""), + test.StringPtr(""), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), DeployedVersionLookup: &deployedver.Lookup{ BasicAuth: &deployedver.BasicAuth{ @@ -2006,7 +2007,7 @@ func TestService_GiveSecrets(t *testing.T) { }, oldService: &Service{ LatestVersion: *latestver.New( - stringPtr("somethingelse"), + test.StringPtr("somethingelse"), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), DeployedVersionLookup: &deployedver.Lookup{ BasicAuth: &deployedver.BasicAuth{ @@ -2039,11 +2040,11 @@ func TestService_GiveSecrets(t *testing.T) { nil, nil, nil)}, }, oldWebHookFails: map[string]*bool{ - "foo": boolPtr(false), - "bar": boolPtr(true)}, + "foo": test.BoolPtr(false), + "bar": test.BoolPtr(true)}, expected: &Service{ LatestVersion: *latestver.New( - stringPtr("somethingelse"), + test.StringPtr("somethingelse"), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), DeployedVersionLookup: &deployedver.Lookup{ BasicAuth: &deployedver.BasicAuth{ @@ -2080,7 +2081,7 @@ func TestService_GiveSecrets(t *testing.T) { "matching secretRefs": { svc: &Service{ LatestVersion: *latestver.New( - stringPtr("somethingelse"), + test.StringPtr("somethingelse"), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), DeployedVersionLookup: &deployedver.Lookup{ BasicAuth: &deployedver.BasicAuth{ @@ -2118,7 +2119,7 @@ func TestService_GiveSecrets(t *testing.T) { }, oldService: &Service{ LatestVersion: *latestver.New( - stringPtr("somethingelse"), + test.StringPtr("somethingelse"), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), DeployedVersionLookup: &deployedver.Lookup{ BasicAuth: &deployedver.BasicAuth{ @@ -2156,7 +2157,7 @@ func TestService_GiveSecrets(t *testing.T) { }, expected: &Service{ LatestVersion: *latestver.New( - stringPtr("somethingelse"), + test.StringPtr("somethingelse"), nil, nil, nil, nil, nil, "", "", nil, nil, nil, nil), DeployedVersionLookup: &deployedver.Lookup{ BasicAuth: &deployedver.BasicAuth{ @@ -2193,9 +2194,9 @@ func TestService_GiveSecrets(t *testing.T) { nil, nil, nil)}, }, secretRefs: oldSecretRefs{ - DeployedVersionLookup: dvSecretRef{Headers: []oldIntIndex{{OldIndex: intPtr(0)}, {OldIndex: intPtr(1)}}}, - Notify: map[string]oldStringIndex{"foo": {OldIndex: stringPtr("foo")}, "bar": {OldIndex: stringPtr("bar")}}, - WebHook: map[string]whSecretRef{"foo": {OldIndex: stringPtr("foo")}, "bar": {OldIndex: stringPtr("bar")}}, + DeployedVersionLookup: dvSecretRef{Headers: []oldIntIndex{{OldIndex: test.IntPtr(0)}, {OldIndex: test.IntPtr(1)}}}, + Notify: map[string]oldStringIndex{"foo": {OldIndex: test.StringPtr("foo")}, "bar": {OldIndex: test.StringPtr("bar")}}, + WebHook: map[string]whSecretRef{"foo": {OldIndex: test.StringPtr("foo")}, "bar": {OldIndex: test.StringPtr("bar")}}, }, }, "unchanged LatestVersion.URL retains Status.LatestVersion": { @@ -2302,11 +2303,11 @@ func TestService_GiveSecrets(t *testing.T) { "http://example.com", nil, nil, nil)}}, oldWebHookFails: map[string]*bool{ - "test": boolPtr(true)}, + "test": test.BoolPtr(true)}, expectedWebHookFails: map[string]*bool{ - "test": boolPtr(true)}, + "test": test.BoolPtr(true)}, secretRefs: oldSecretRefs{ - WebHook: map[string]whSecretRef{"test": {OldIndex: stringPtr("test")}}}, + WebHook: map[string]whSecretRef{"test": {OldIndex: test.StringPtr("test")}}}, }, "changed WebHook loses Failed": { svc: &Service{ @@ -2328,9 +2329,9 @@ func TestService_GiveSecrets(t *testing.T) { "http://example.com/other", nil, nil, nil)}}, oldWebHookFails: map[string]*bool{ - "test": boolPtr(true)}, + "test": test.BoolPtr(true)}, secretRefs: oldSecretRefs{ - WebHook: map[string]whSecretRef{"test": {OldIndex: stringPtr("test")}}}, + WebHook: map[string]whSecretRef{"test": {OldIndex: test.StringPtr("test")}}}, }, "unchanged Command retains Failed": { svc: &Service{ @@ -2345,9 +2346,9 @@ func TestService_GiveSecrets(t *testing.T) { {"ls", "-la"}}, CommandController: &command.Controller{}}, oldCommandFails: []*bool{ - boolPtr(true)}, + test.BoolPtr(true)}, expectedCommandFails: []*bool{ - boolPtr(true)}, + test.BoolPtr(true)}, secretRefs: oldSecretRefs{}, }, "changed Command loses Failed": { @@ -2362,7 +2363,7 @@ func TestService_GiveSecrets(t *testing.T) { Command: command.Slice{ {"ls", "-lah"}}}, oldCommandFails: []*bool{ - boolPtr(true)}, + test.BoolPtr(true)}, secretRefs: oldSecretRefs{}, }, } @@ -2548,7 +2549,7 @@ func TestFromPayload(t *testing.T) { want: &Service{ Dashboard: DashboardOptions{Defaults: &DashboardOptionsDefaults{}}, Options: opt.Options{ - Active: boolPtr(false), + Active: test.BoolPtr(false), Defaults: &opt.OptionsDefaults{}}, LatestVersion: latestver.Lookup{Defaults: &latestver.LookupDefaults{}}}, }, @@ -2602,7 +2603,7 @@ func TestFromPayload(t *testing.T) { Options: opt.Options{Defaults: &opt.OptionsDefaults{}}, Dashboard: DashboardOptions{Defaults: &DashboardOptionsDefaults{}}, LatestVersion: *latestver.New( - stringPtr("aToken"), + test.StringPtr("aToken"), nil, nil, nil, &filter.Require{ Docker: filter.NewDockerCheck( @@ -2610,7 +2611,7 @@ func TestFromPayload(t *testing.T) { nil, "", "", nil, nil, nil, nil)}, oldService: &Service{ LatestVersion: *latestver.New( - stringPtr("aToken"), + test.StringPtr("aToken"), nil, nil, nil, &filter.Require{ Docker: filter.NewDockerCheck( @@ -2636,7 +2637,7 @@ func TestFromPayload(t *testing.T) { Options: opt.Options{Defaults: &opt.OptionsDefaults{}}, Dashboard: DashboardOptions{Defaults: &DashboardOptionsDefaults{}}, LatestVersion: *latestver.New( - stringPtr("aToken"), + test.StringPtr("aToken"), nil, nil, nil, &filter.Require{ Docker: filter.NewDockerCheck( @@ -2650,7 +2651,7 @@ func TestFromPayload(t *testing.T) { }, oldService: &Service{ LatestVersion: *latestver.New( - stringPtr("aToken"), + test.StringPtr("aToken"), nil, nil, nil, &filter.Require{ Docker: filter.NewDockerCheck( @@ -2717,7 +2718,7 @@ func TestFromPayload(t *testing.T) { Options: opt.Options{Defaults: &opt.OptionsDefaults{}}, Dashboard: DashboardOptions{Defaults: &DashboardOptionsDefaults{}}, LatestVersion: *latestver.New( - stringPtr("aToken"), + test.StringPtr("aToken"), nil, nil, nil, &filter.Require{ Docker: filter.NewDockerCheck( @@ -2772,7 +2773,7 @@ func TestFromPayload(t *testing.T) { }, oldService: &Service{ LatestVersion: *latestver.New( - stringPtr("aToken"), + test.StringPtr("aToken"), nil, nil, nil, &filter.Require{ Docker: filter.NewDockerCheck( @@ -2907,7 +2908,7 @@ func TestFromPayload(t *testing.T) { Options: opt.Options{Defaults: &opt.OptionsDefaults{}}, Dashboard: DashboardOptions{Defaults: &DashboardOptionsDefaults{}}, LatestVersion: *latestver.New( - stringPtr("aToken"), + test.StringPtr("aToken"), nil, nil, nil, &filter.Require{ Docker: filter.NewDockerCheck( @@ -2982,7 +2983,7 @@ func TestFromPayload(t *testing.T) { }, oldService: &Service{ LatestVersion: *latestver.New( - stringPtr("aToken"), + test.StringPtr("aToken"), nil, nil, nil, &filter.Require{ Docker: filter.NewDockerCheck( @@ -3076,7 +3077,7 @@ func TestFromPayload(t *testing.T) { t.Parallel() // Convert the string payload to a ReadCloser - tc.payload = trimJSON(tc.payload) + tc.payload = test.TrimJSON(tc.payload) reader := bytes.NewReader([]byte(tc.payload)) payload := io.NopCloser(reader) if tc.serviceHardDefaults == nil { @@ -3138,7 +3139,7 @@ func TestFromPayload(t *testing.T) { func TestService_CheckFetches(t *testing.T) { // GIVEN a Service - testLV := testLatestVersionLookupURL(false) + testLV := testLatestVersion("url", false) testLV.Query(false, &util.LogFrom{}) testDVL := testDeployedVersionLookup(false) v, _ := testDVL.Query(false, &util.LogFrom{}) @@ -3153,7 +3154,7 @@ func TestService_CheckFetches(t *testing.T) { }{ "Already have LatestVersion, nil DeployedVersionLookup": { svc: &Service{ - LatestVersion: *testLatestVersionLookupURL(false), + LatestVersion: *testLatestVersion("url", false), DeployedVersionLookup: nil}, startLatestVersion: "foo", wantLatestVersion: testLV.Status.LatestVersion(), @@ -3163,7 +3164,7 @@ func TestService_CheckFetches(t *testing.T) { }, "Already have LatestVersion and DeployedVersionLookup": { svc: &Service{ - LatestVersion: *testLatestVersionLookupURL(false), + LatestVersion: *testLatestVersion("url", false), DeployedVersionLookup: testDeployedVersionLookup(false)}, startLatestVersion: "foo", wantLatestVersion: testLV.Status.LatestVersion(), @@ -3173,20 +3174,20 @@ func TestService_CheckFetches(t *testing.T) { }, "latest_version query fails": { svc: &Service{ - LatestVersion: *testLatestVersionLookupURL(true), + LatestVersion: *testLatestVersion("url", true), DeployedVersionLookup: testDeployedVersionLookup(false)}, errRegex: `latest_version - x509 \(certificate invalid\)`, }, "deployed_version query fails": { svc: &Service{ - LatestVersion: *testLatestVersionLookupURL(false), + LatestVersion: *testLatestVersion("url", false), DeployedVersionLookup: testDeployedVersionLookup(true)}, wantLatestVersion: "1.2.2", errRegex: `deployed_version - x509 \(certificate invalid\)`, }, "both queried": { svc: &Service{ - LatestVersion: *testLatestVersionLookupURL(false), + LatestVersion: *testLatestVersion("url", false), DeployedVersionLookup: testDeployedVersionLookup(false)}, wantLatestVersion: "1.2.2", wantDeployedVersion: "1.2.3", @@ -3195,10 +3196,10 @@ func TestService_CheckFetches(t *testing.T) { "inactive queries neither": { svc: &Service{ Options: *opt.New( - boolPtr(false), // active + test.BoolPtr(false), // active "", nil, nil, nil), - LatestVersion: *testLatestVersionLookupURL(false), + LatestVersion: *testLatestVersion("url", false), DeployedVersionLookup: testDeployedVersionLookup(false)}, errRegex: "^$", }, @@ -3214,7 +3215,7 @@ func TestService_CheckFetches(t *testing.T) { "", nil)}, &Defaults{ Options: *opt.NewDefaults( - "0h", boolPtr(true))}, + "0h", test.BoolPtr(true))}, &shoutrrr.SliceDefaults{}, &shoutrrr.SliceDefaults{}, &shoutrrr.SliceDefaults{}, &webhook.SliceDefaults{}, &webhook.WebHookDefaults{}, &webhook.WebHookDefaults{}, ) diff --git a/service/options/help_test.go b/service/options/help_test.go index a3fd8a76..5880772b 100644 --- a/service/options/help_test.go +++ b/service/options/help_test.go @@ -16,15 +16,10 @@ package opt -func boolPtr(val bool) *bool { - return &val -} -func stringPtr(val string) *string { - return &val -} +import "github.com/release-argus/Argus/test" func testOptions() *Options { return New( - boolPtr(true), "10m", boolPtr(true), + test.BoolPtr(true), "10m", test.BoolPtr(true), &OptionsDefaults{}, &OptionsDefaults{}) } diff --git a/service/options/options_test.go b/service/options/options_test.go index 21e52094..f8be6d53 100644 --- a/service/options/options_test.go +++ b/service/options/options_test.go @@ -22,6 +22,7 @@ import ( "testing" "time" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) @@ -35,10 +36,10 @@ func TestOptions_GetActive(t *testing.T) { active: nil, want: true}, "true": { - active: boolPtr(true), + active: test.BoolPtr(true), want: true}, "false": { - active: boolPtr(false), + active: test.BoolPtr(false), want: false}, } @@ -120,18 +121,18 @@ func TestOptions_GetSemanticVersioning(t *testing.T) { }{ "root overrides all": { wantBool: true, - root: boolPtr(true), - dfault: boolPtr(false), - hardDefault: boolPtr(false), + root: test.BoolPtr(true), + dfault: test.BoolPtr(false), + hardDefault: test.BoolPtr(false), }, "default overrides hardDefault": { wantBool: true, - dfault: boolPtr(true), - hardDefault: boolPtr(false), + dfault: test.BoolPtr(true), + hardDefault: test.BoolPtr(false), }, "hardDefault is last resort": { wantBool: true, - hardDefault: boolPtr(true), + hardDefault: test.BoolPtr(true), }, } @@ -225,20 +226,20 @@ func TestOptions_CheckValues(t *testing.T) { "valid options": { errRegex: `^$`, options: New( - boolPtr(false), "10s", boolPtr(false), + test.BoolPtr(false), "10s", test.BoolPtr(false), nil, nil), }, "invalid interval": { errRegex: `interval: .* `, options: New( - boolPtr(false), "10x", boolPtr(false), + test.BoolPtr(false), "10x", test.BoolPtr(false), nil, nil), }, "seconds get appended to pure decimal interval": { errRegex: `^$`, wantInterval: "10s", options: New( - boolPtr(false), "10", boolPtr(false), + test.BoolPtr(false), "10", test.BoolPtr(false), nil, nil), }, } @@ -277,7 +278,7 @@ func TestOptions_String(t *testing.T) { }, "all options defined": { options: New( - boolPtr(true), "10s", boolPtr(true), + test.BoolPtr(true), "10s", test.BoolPtr(true), nil, nil), want: ` interval: 10s @@ -288,15 +289,15 @@ active: true "empty with defaults": { options: &Options{ Defaults: NewDefaults( - "10s", boolPtr(true))}, + "10s", test.BoolPtr(true))}, want: "{}\n", }, "all with defaults": { options: New( - boolPtr(true), "10s", boolPtr(true), + test.BoolPtr(true), "10s", test.BoolPtr(true), nil, NewDefaults( - "1h", boolPtr(false))), + "1h", test.BoolPtr(false))), want: ` interval: 10s semantic_versioning: true @@ -306,15 +307,15 @@ active: true "empty with hardDefaults": { options: &Options{ HardDefaults: NewDefaults( - "10s", boolPtr(true))}, + "10s", test.BoolPtr(true))}, want: "{}\n", }, "all with hardDefaults": { options: New( - boolPtr(true), "10s", boolPtr(true), + test.BoolPtr(true), "10s", test.BoolPtr(true), nil, NewDefaults( - "1h", boolPtr(false))), + "1h", test.BoolPtr(false))), want: ` interval: 10s semantic_versioning: true @@ -325,16 +326,16 @@ active: true options: New( nil, "", nil, NewDefaults( - "10s", boolPtr(true)), - NewDefaults("1h", boolPtr(false))), + "10s", test.BoolPtr(true)), + NewDefaults("1h", test.BoolPtr(false))), want: "{}\n", }, "all with defaults and hardDefaults": { options: New( - boolPtr(true), "10s", boolPtr(true), + test.BoolPtr(true), "10s", test.BoolPtr(true), NewDefaults( - "20s", boolPtr(true)), - NewDefaults("30s", boolPtr(false))), + "20s", test.BoolPtr(true)), + NewDefaults("30s", test.BoolPtr(false))), want: ` interval: 10s semantic_versioning: true diff --git a/service/status/fails_test.go b/service/status/fails_test.go index d14bfe46..9268ec4f 100644 --- a/service/status/fails_test.go +++ b/service/status/fails_test.go @@ -20,6 +20,8 @@ import ( "strconv" "strings" "testing" + + "github.com/release-argus/Argus/test" ) func TestFailsBase_Init(t *testing.T) { @@ -75,19 +77,19 @@ func TestFailsBase_SetAndGet(t *testing.T) { size: 0, setAtArray: map[int]*bool{}, setAtMap: map[string]*bool{ - "test": boolPtr(true)}, + "test": test.BoolPtr(true)}, }, "can add to non-empty map or edit array": { size: 3, setAtArray: map[int]*bool{ - 0: boolPtr(true), - 1: boolPtr(false), - 2: boolPtr(true), + 0: test.BoolPtr(true), + 1: test.BoolPtr(false), + 2: test.BoolPtr(true), }, setAtMap: map[string]*bool{ - "bish": boolPtr(true), - "bash": boolPtr(false), - "bosh": boolPtr(true)}, + "bish": test.BoolPtr(true), + "bash": test.BoolPtr(false), + "bosh": test.BoolPtr(true)}, }, } @@ -170,16 +172,16 @@ func TestFailsBase_AllPassed(t *testing.T) { }, "all true (failed)": { fails: map[int]*bool{ - 0: boolPtr(true), - 1: boolPtr(true), - 2: boolPtr(true)}, + 0: test.BoolPtr(true), + 1: test.BoolPtr(true), + 2: test.BoolPtr(true)}, want: false, }, "all false (passed)": { fails: map[int]*bool{ - 0: boolPtr(false), - 1: boolPtr(false), - 2: boolPtr(false)}, + 0: test.BoolPtr(false), + 1: test.BoolPtr(false), + 2: test.BoolPtr(false)}, want: true, }, "all nil (not run)": { @@ -191,8 +193,8 @@ func TestFailsBase_AllPassed(t *testing.T) { }, "mixed": { fails: map[int]*bool{ - 0: boolPtr(true), - 1: boolPtr(false), + 0: test.BoolPtr(true), + 1: test.BoolPtr(false), 2: nil}, want: false, }, @@ -246,15 +248,15 @@ func TestFailsBase_Reset(t *testing.T) { }, "all true (failed)": { fails: map[int]*bool{ - 0: boolPtr(true), - 1: boolPtr(true), - 2: boolPtr(true)}, + 0: test.BoolPtr(true), + 1: test.BoolPtr(true), + 2: test.BoolPtr(true)}, }, "all false (passed)": { fails: map[int]*bool{ - 0: boolPtr(false), - 1: boolPtr(false), - 2: boolPtr(false)}, + 0: test.BoolPtr(false), + 1: test.BoolPtr(false), + 2: test.BoolPtr(false)}, }, "all nil (not run)": { fails: map[int]*bool{ @@ -264,8 +266,8 @@ func TestFailsBase_Reset(t *testing.T) { }, "mixed": { fails: map[int]*bool{ - 0: boolPtr(true), - 1: boolPtr(false), + 0: test.BoolPtr(true), + 1: test.BoolPtr(false), 2: nil}, }, } @@ -325,28 +327,28 @@ func TestFailsBase_Length(t *testing.T) { size: 0, setAtArray: map[int]*bool{}, setAtMap: map[string]*bool{ - "test": boolPtr(true)}, + "test": test.BoolPtr(true)}, }, "can add to non-empty map or edit array": { size: 3, setAtArray: map[int]*bool{ - 0: boolPtr(true), - 1: boolPtr(false), - 2: boolPtr(true), + 0: test.BoolPtr(true), + 1: test.BoolPtr(false), + 2: test.BoolPtr(true), }, setAtMap: map[string]*bool{ - "bish": boolPtr(true), - "bash": boolPtr(false), - "bosh": boolPtr(true)}, + "bish": test.BoolPtr(true), + "bash": test.BoolPtr(false), + "bosh": test.BoolPtr(true)}, }, "length gives number of elements in map, not make size": { size: 3, setAtArray: map[int]*bool{ - 0: boolPtr(true), - 1: boolPtr(false)}, + 0: test.BoolPtr(true), + 1: test.BoolPtr(false)}, setAtMap: map[string]*bool{ - "bish": boolPtr(true), - "bash": boolPtr(false)}, + "bish": test.BoolPtr(true), + "bash": test.BoolPtr(false)}, }, } @@ -406,13 +408,13 @@ func TestFails_String(t *testing.T) { }, "no fails": { commandFails: []*bool{ - nil, boolPtr(false)}, + nil, test.BoolPtr(false)}, shoutrrrFails: map[string]*bool{ - "bar": boolPtr(false), + "bar": test.BoolPtr(false), "foo": nil}, webhookFails: map[string]*bool{ "bar": nil, - "foo": boolPtr(false)}, + "foo": test.BoolPtr(false)}, want: ` shoutrrr: {bar: false, foo: nil}, command: [0: nil, 1: false], @@ -420,41 +422,41 @@ shoutrrr: {bar: false, foo: nil}, }, "only shoutrrr": { shoutrrrFails: map[string]*bool{ - "bash": boolPtr(false), + "bash": test.BoolPtr(false), "bish": nil, - "bosh": boolPtr(true)}, + "bosh": test.BoolPtr(true)}, want: ` shoutrrr: {bash: false, bish: nil, bosh: true}`, }, "only command": { commandFails: []*bool{ nil, - boolPtr(false), - boolPtr(true)}, + test.BoolPtr(false), + test.BoolPtr(true)}, want: ` command: [0: nil, 1: false, 2: true]`, }, "only webhook": { webhookFails: map[string]*bool{ - "bash": boolPtr(true), - "bish": boolPtr(false), + "bash": test.BoolPtr(true), + "bish": test.BoolPtr(false), "bosh": nil}, want: ` webhook: {bash: true, bish: false, bosh: nil}`, }, "all": { shoutrrrFails: map[string]*bool{ - "bash": boolPtr(false), - "bish": boolPtr(true), + "bash": test.BoolPtr(false), + "bish": test.BoolPtr(true), "bosh": nil}, commandFails: []*bool{ nil, - boolPtr(false), - boolPtr(true)}, + test.BoolPtr(false), + test.BoolPtr(true)}, webhookFails: map[string]*bool{ - "bash": boolPtr(false), + "bash": test.BoolPtr(false), "bish": nil, - "bosh": boolPtr(true)}, + "bosh": test.BoolPtr(true)}, want: ` shoutrrr: {bash: false, bish: true, bosh: nil}, command: [0: nil, 1: false, 2: true], @@ -462,17 +464,17 @@ shoutrrr: {bash: false, bish: true, bosh: nil}, }, "maps are alphabetical": { shoutrrrFails: map[string]*bool{ - "bish": boolPtr(true), - "bash": boolPtr(true), - "bosh": boolPtr(true)}, + "bish": test.BoolPtr(true), + "bash": test.BoolPtr(true), + "bosh": test.BoolPtr(true)}, commandFails: []*bool{ nil, - boolPtr(true), - boolPtr(false)}, + test.BoolPtr(true), + test.BoolPtr(false)}, webhookFails: map[string]*bool{ - "zip": boolPtr(true), - "zap": boolPtr(true), - "zoop": boolPtr(true)}, + "zip": test.BoolPtr(true), + "zap": test.BoolPtr(true), + "zoop": test.BoolPtr(true)}, want: ` shoutrrr: {bash: true, bish: true, bosh: true}, command: [0: nil, 1: true, 2: false], diff --git a/service/status/help_test.go b/service/status/help_test.go index d55425de..167e8754 100644 --- a/service/status/help_test.go +++ b/service/status/help_test.go @@ -18,15 +18,9 @@ package svcstatus import ( dbtype "github.com/release-argus/Argus/db/types" + "github.com/release-argus/Argus/test" ) -func boolPtr(val bool) *bool { - return &val -} -func stringPtr(val string) *string { - return &val -} - func testStatus() (status *Status) { var ( announceChannel chan []byte = make(chan []byte, 2) @@ -37,12 +31,12 @@ func testStatus() (status *Status) { &announceChannel, &databaseChannel, &saveChannel, "", "", "", "", "", "") status = svcStatus - status.ServiceID = stringPtr("test") - status.WebURL = stringPtr("") + status.ServiceID = test.StringPtr("test") + status.WebURL = test.StringPtr("") status.Init( 0, 0, 0, - stringPtr("test-service"), - stringPtr("http://example.com")) + test.StringPtr("test-service"), + test.StringPtr("http://example.com")) status.SetApprovedVersion("1.1.1", false) status.SetLatestVersion("2.2.2", false) status.SetLatestVersionTimestamp("2002-02-02T02:02:02Z") diff --git a/service/status/status_test.go b/service/status/status_test.go index 9016d5f7..2eb50144 100644 --- a/service/status/status_test.go +++ b/service/status/status_test.go @@ -24,6 +24,7 @@ import ( "github.com/prometheus/client_golang/prometheus/testutil" dbtype "github.com/release-argus/Argus/db/types" + "github.com/release-argus/Argus/test" metric "github.com/release-argus/Argus/web/metrics" ) @@ -127,16 +128,16 @@ func TestStatus_GetWebURL(t *testing.T) { want string }{ "nil string": { - webURL: stringPtr(""), + webURL: test.StringPtr(""), want: ""}, "empty string": { - webURL: stringPtr(""), + webURL: test.StringPtr(""), want: ""}, "string without templating": { - webURL: stringPtr("https://something.com/somewhere"), + webURL: test.StringPtr("https://something.com/somewhere"), want: "https://something.com/somewhere"}, "string with templating": { - webURL: stringPtr("https://something.com/somewhere/{{ version }}"), + webURL: test.StringPtr("https://something.com/somewhere/{{ version }}"), want: "https://something.com/somewhere/" + latestVersion}, } @@ -212,8 +213,8 @@ func TestStatus_ApprovedVersion(t *testing.T) { "", "", "", "", "", "") status.Init( 0, 0, 0, - stringPtr("TestStatus_SetApprovedVersion_"+name), - stringPtr("https://example.com")) + test.StringPtr("TestStatus_SetApprovedVersion_"+name), + test.StringPtr("https://example.com")) status.SetLatestVersion(latestVersion, false) status.SetDeployedVersion(deployedVersion, false) @@ -305,7 +306,7 @@ func TestStatus_DeployedVersion(t *testing.T) { status.Init( 0, 0, 0, &name, - stringPtr("http://example.com")) + test.StringPtr("http://example.com")) status.SetApprovedVersion(approvedVersion, haveDB) status.SetDeployedVersion(deployedVersion, haveDB) status.SetLatestVersion(latestVersion, haveDB) @@ -388,7 +389,7 @@ func TestStatus_LatestVersion(t *testing.T) { status.Init( 0, 0, 0, &name, - stringPtr("http://example.com")) + test.StringPtr("http://example.com")) status.SetApprovedVersion(approvedVersion, haveDB) status.SetDeployedVersion(deployedVersion, haveDB) status.SetLatestVersion(latestVersion, haveDB) @@ -674,31 +675,31 @@ func TestFails_ResetFails(t *testing.T) { "only notifies": { shoutrrrFails: &map[string]*bool{ "0": nil, - "1": boolPtr(false), - "3": boolPtr(true)}, + "1": test.BoolPtr(false), + "3": test.BoolPtr(true)}, }, "only commands": { commandFails: &[]*bool{ nil, - boolPtr(false), - boolPtr(true)}, + test.BoolPtr(false), + test.BoolPtr(true)}, }, "only webhooks": { webhookFails: &map[string]*bool{ "0": nil, - "1": boolPtr(false), - "3": boolPtr(true)}, + "1": test.BoolPtr(false), + "3": test.BoolPtr(true)}, }, "all filled": { shoutrrrFails: &map[string]*bool{ "0": nil, - "1": boolPtr(false), - "3": boolPtr(true)}, - commandFails: &[]*bool{nil, boolPtr(false), boolPtr(true)}, + "1": test.BoolPtr(false), + "3": test.BoolPtr(true)}, + commandFails: &[]*bool{nil, test.BoolPtr(false), test.BoolPtr(true)}, webhookFails: &map[string]*bool{ "0": nil, - "1": boolPtr(false), - "3": boolPtr(true)}, + "1": test.BoolPtr(false), + "3": test.BoolPtr(true)}, }, } @@ -773,15 +774,15 @@ func TestStatus_String(t *testing.T) { "only fails": { commandFails: []*bool{ nil, - boolPtr(false), - boolPtr(true)}, + test.BoolPtr(false), + test.BoolPtr(true)}, shoutrrrFails: map[string]*bool{ - "bash": boolPtr(false), + "bash": test.BoolPtr(false), "bish": nil, - "bosh": boolPtr(true)}, + "bosh": test.BoolPtr(true)}, webhookFails: map[string]*bool{ "bar": nil, - "foo": boolPtr(false)}, + "foo": test.BoolPtr(false)}, status: &Status{}, want: ` fails: { @@ -796,21 +797,21 @@ shoutrrr: {bash: false, bish: nil, bosh: true}, status: &Status{}, shoutrrrFails: map[string]*bool{ "bish": nil, - "bash": boolPtr(false), - "bosh": boolPtr(true)}, + "bash": test.BoolPtr(false), + "bosh": test.BoolPtr(true)}, commandFails: []*bool{ nil, - boolPtr(false), - boolPtr(true)}, + test.BoolPtr(false), + test.BoolPtr(true)}, webhookFails: map[string]*bool{ - "foo": boolPtr(false), + "foo": test.BoolPtr(false), "bar": nil}, approvedVersion: "1.2.4", deployedVersion: "1.2.3", deployedVersionTimestamp: "2022-01-01T01:01:02Z", latestVersion: "1.2.4", latestVersionTimestamp: "2022-01-01T01:01:01Z", - lastQueried: stringPtr("2022-01-01T01:01:01Z"), + lastQueried: test.StringPtr("2022-01-01T01:01:01Z"), want: ` approved_version: 1.2.4, deployed_version: 1.2.3, @@ -906,7 +907,7 @@ func TestStatus_SetLatestVersionIsDeployedMetric(t *testing.T) { status.Init( 0, 0, 0, &name, - stringPtr("http://example.com")) + test.StringPtr("http://example.com")) status.SetLatestVersion(tc.latestVersion, false) status.SetDeployedVersion(tc.deployedVersion, false) @@ -949,7 +950,7 @@ func TestStatus_InitMetrics_DeleteMetrics(t *testing.T) { status.Init( 0, 0, 0, &name, - stringPtr("http://example.com")) + test.StringPtr("http://example.com")) status.SetLatestVersion("0.0.2", false) status.SetDeployedVersion("0.0.2", false) if tc.nilServiceID { diff --git a/service/track_test.go b/service/track_test.go index 0af62ff7..6f5951be 100644 --- a/service/track_test.go +++ b/service/track_test.go @@ -24,10 +24,12 @@ import ( "github.com/prometheus/client_golang/prometheus/testutil" "github.com/release-argus/Argus/notifiers/shoutrrr" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" api_type "github.com/release-argus/Argus/web/api/types" metric "github.com/release-argus/Argus/web/metrics" "github.com/release-argus/Argus/webhook" + test_webhook "github.com/release-argus/Argus/webhook/test" ) func TestSlice_Track(t *testing.T) { @@ -55,12 +57,12 @@ func TestSlice_Track(t *testing.T) { for _, j := range tc.slice { switch j { case "github": - (*slice)[j] = testServiceGitHub(name) + (*slice)[j] = testService(name, "github") case "url": - (*slice)[j] = testServiceURL(name) + (*slice)[j] = testService(name, "url") } if len(tc.active) != 0 { - (*slice)[j].Options.Active = boolPtr(tc.active[i]) + (*slice)[j].Options.Active = test.BoolPtr(tc.active[i]) } (*slice)[j].Status.SetLatestVersion("", false) (*slice)[j].Status.SetDeployedVersion("", false) @@ -132,7 +134,7 @@ func TestService_Track(t *testing.T) { wantDatabaseMesages: 2, // db: 1 for deployed, 1 for latest }, "first query updates LatestVersion and DeployedVersion with active true": { - livenessMetric: 1, active: boolPtr(true), + livenessMetric: 1, active: test.BoolPtr(true), startLatestVersion: "", startDeployedVersion: "", wantLatestVersion: "1.2.2", wantDeployedVersion: "1.2.2", wantAnnounces: 1, // announce: 1 for latest query @@ -147,7 +149,7 @@ func TestService_Track(t *testing.T) { }, "query finds a newer version and updates LatestVersion and not DeployedVersion": { urlRegex: "v([0-9.]+)", livenessMetric: 1, - webhook: testWebHook(false), + webhook: test_webhook.WebHook(false, false, false), startLatestVersion: "1.2.1", startDeployedVersion: "1.2.1", wantLatestVersion: "1.2.2", wantDeployedVersion: "1.2.1", wantAnnounces: 1, // announce: 1 for latest query @@ -155,7 +157,7 @@ func TestService_Track(t *testing.T) { }, "query finds a newer version does send webhooks if autoApprove enabled": { urlRegex: "v([0-9.]+)", livenessMetric: 1, - webhook: testWebHook(false), + webhook: test_webhook.WebHook(false, false, false), autoApprove: true, startLatestVersion: "1.2.1", startDeployedVersion: "1.2.1", wantLatestVersion: "1.2.2", wantDeployedVersion: "1.2.2", @@ -245,7 +247,7 @@ func TestService_Track(t *testing.T) { wantDatabaseMesages: 0, // db: 0 for nothing changing }, "inactive service doesn't track": { - livenessMetric: 0, active: boolPtr(false), + livenessMetric: 0, active: test.BoolPtr(false), startLatestVersion: "", startDeployedVersion: "", wantLatestVersion: "", wantDeployedVersion: "", wantAnnounces: 0, wantDatabaseMesages: 0, @@ -262,7 +264,7 @@ func TestService_Track(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - svc := testServiceURL(name) + svc := testService(name, "url") if tc.deleting { svc.Status.SetDeleting() } diff --git a/service/types_test.go b/service/types_test.go index 8c8c48e3..c4ce0a19 100644 --- a/service/types_test.go +++ b/service/types_test.go @@ -26,6 +26,7 @@ import ( latestver "github.com/release-argus/Argus/service/latest_version" opt "github.com/release-argus/Argus/service/options" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" apitype "github.com/release-argus/Argus/web/api/types" "github.com/release-argus/Argus/webhook" ) @@ -47,7 +48,7 @@ func TestService_String(t *testing.T) { svc: &Service{ Comment: "svc for blah", Options: opt.Options{ - Active: boolPtr(false)}, + Active: test.BoolPtr(false)}, LatestVersion: latestver.Lookup{ URL: "release-argus/Argus"}, DeployedVersionLookup: &deployedver.Lookup{ @@ -68,14 +69,14 @@ func TestService_String(t *testing.T) { "https://example.com", nil, nil, nil)}, Dashboard: *NewDashboardOptions( - boolPtr(true), "", "", "", + test.BoolPtr(true), "", "", "", nil, nil), Defaults: &Defaults{ Options: *opt.NewDefaults( - "", boolPtr(false))}, + "", test.BoolPtr(false))}, HardDefaults: &Defaults{ Options: *opt.NewDefaults( - "", boolPtr(false))}}, + "", test.BoolPtr(false))}}, want: ` comment: svc for blah options: @@ -147,12 +148,12 @@ func TestService_Summary(t *testing.T) { "empty": { svc: &Service{}, want: &apitype.ServiceSummary{ - Type: stringPtr(""), - Icon: stringPtr(""), - IconLinkTo: stringPtr(""), - HasDeployedVersionLookup: boolPtr(false), - Command: intPtr(0), - WebHook: intPtr(0), + Type: test.StringPtr(""), + Icon: test.StringPtr(""), + IconLinkTo: test.StringPtr(""), + HasDeployedVersionLookup: test.BoolPtr(false), + Command: test.IntPtr(0), + WebHook: test.IntPtr(0), Status: &apitype.Status{}}, }, "only id": { @@ -160,26 +161,26 @@ func TestService_Summary(t *testing.T) { ID: "foo"}, want: &apitype.ServiceSummary{ ID: "foo", - Type: stringPtr(""), - Icon: stringPtr(""), - IconLinkTo: stringPtr(""), - HasDeployedVersionLookup: boolPtr(false), - Command: intPtr(0), - WebHook: intPtr(0), + Type: test.StringPtr(""), + Icon: test.StringPtr(""), + IconLinkTo: test.StringPtr(""), + HasDeployedVersionLookup: test.BoolPtr(false), + Command: test.IntPtr(0), + WebHook: test.IntPtr(0), Status: &apitype.Status{}}, }, "only options.active": { svc: &Service{ Options: opt.Options{ - Active: boolPtr(false)}}, + Active: test.BoolPtr(false)}}, want: &apitype.ServiceSummary{ - Active: boolPtr(false), - Type: stringPtr(""), - Icon: stringPtr(""), - IconLinkTo: stringPtr(""), - HasDeployedVersionLookup: boolPtr(false), - Command: intPtr(0), - WebHook: intPtr(0), + Active: test.BoolPtr(false), + Type: test.StringPtr(""), + Icon: test.StringPtr(""), + IconLinkTo: test.StringPtr(""), + HasDeployedVersionLookup: test.BoolPtr(false), + Command: test.IntPtr(0), + WebHook: test.IntPtr(0), Status: &apitype.Status{}}, }, "only latest_version.type": { @@ -187,12 +188,12 @@ func TestService_Summary(t *testing.T) { LatestVersion: latestver.Lookup{ Type: "github"}}, want: &apitype.ServiceSummary{ - Type: stringPtr("github"), - Icon: stringPtr(""), - IconLinkTo: stringPtr(""), - HasDeployedVersionLookup: boolPtr(false), - Command: intPtr(0), - WebHook: intPtr(0), + Type: test.StringPtr("github"), + Icon: test.StringPtr(""), + IconLinkTo: test.StringPtr(""), + HasDeployedVersionLookup: test.BoolPtr(false), + Command: test.IntPtr(0), + WebHook: test.IntPtr(0), Status: &apitype.Status{}}, }, "only dashboard.icon, and it's a url": { @@ -200,12 +201,12 @@ func TestService_Summary(t *testing.T) { Dashboard: DashboardOptions{ Icon: "https://example.com/icon.png"}}, want: &apitype.ServiceSummary{ - Type: stringPtr(""), - Icon: stringPtr("https://example.com/icon.png"), - IconLinkTo: stringPtr(""), - HasDeployedVersionLookup: boolPtr(false), - Command: intPtr(0), - WebHook: intPtr(0), + Type: test.StringPtr(""), + Icon: test.StringPtr("https://example.com/icon.png"), + IconLinkTo: test.StringPtr(""), + HasDeployedVersionLookup: test.BoolPtr(false), + Command: test.IntPtr(0), + WebHook: test.IntPtr(0), Status: &apitype.Status{}}, }, "only dashboard.icon, and it's not a url": { @@ -213,12 +214,12 @@ func TestService_Summary(t *testing.T) { Dashboard: DashboardOptions{ Icon: "smile"}}, want: &apitype.ServiceSummary{ - Type: stringPtr(""), - Icon: stringPtr(""), - IconLinkTo: stringPtr(""), - HasDeployedVersionLookup: boolPtr(false), - Command: intPtr(0), - WebHook: intPtr(0), + Type: test.StringPtr(""), + Icon: test.StringPtr(""), + IconLinkTo: test.StringPtr(""), + HasDeployedVersionLookup: test.BoolPtr(false), + Command: test.IntPtr(0), + WebHook: test.IntPtr(0), Status: &apitype.Status{}}, }, "only dashboard.icon, from notify": { @@ -236,12 +237,12 @@ func TestService_Summary(t *testing.T) { shoutrrr.NewDefaults( "", nil, nil, nil))}}, want: &apitype.ServiceSummary{ - Type: stringPtr(""), - Icon: stringPtr("https://example.com/notify.png"), - IconLinkTo: stringPtr(""), - HasDeployedVersionLookup: boolPtr(false), - Command: intPtr(0), - WebHook: intPtr(0), + Type: test.StringPtr(""), + Icon: test.StringPtr("https://example.com/notify.png"), + IconLinkTo: test.StringPtr(""), + HasDeployedVersionLookup: test.BoolPtr(false), + Command: test.IntPtr(0), + WebHook: test.IntPtr(0), Status: &apitype.Status{}}, }, "only dashboard.icon, dashboard overrides notify": { @@ -261,12 +262,12 @@ func TestService_Summary(t *testing.T) { shoutrrr.NewDefaults( "", nil, nil, nil))}}, want: &apitype.ServiceSummary{ - Type: stringPtr(""), - Icon: stringPtr("https://example.com/icon.png"), - IconLinkTo: stringPtr(""), - HasDeployedVersionLookup: boolPtr(false), - Command: intPtr(0), - WebHook: intPtr(0), + Type: test.StringPtr(""), + Icon: test.StringPtr("https://example.com/icon.png"), + IconLinkTo: test.StringPtr(""), + HasDeployedVersionLookup: test.BoolPtr(false), + Command: test.IntPtr(0), + WebHook: test.IntPtr(0), Status: &apitype.Status{}}, }, "only dashboard.icon_link_to": { @@ -274,36 +275,36 @@ func TestService_Summary(t *testing.T) { Dashboard: DashboardOptions{ IconLinkTo: "https://example.com"}}, want: &apitype.ServiceSummary{ - Type: stringPtr(""), - Icon: stringPtr(""), - IconLinkTo: stringPtr("https://example.com"), - HasDeployedVersionLookup: boolPtr(false), - Command: intPtr(0), - WebHook: intPtr(0), + Type: test.StringPtr(""), + Icon: test.StringPtr(""), + IconLinkTo: test.StringPtr("https://example.com"), + HasDeployedVersionLookup: test.BoolPtr(false), + Command: test.IntPtr(0), + WebHook: test.IntPtr(0), Status: &apitype.Status{}}, }, "only deployed_version": { svc: &Service{ DeployedVersionLookup: &deployedver.Lookup{}}, want: &apitype.ServiceSummary{ - Type: stringPtr(""), - Icon: stringPtr(""), - IconLinkTo: stringPtr(""), - HasDeployedVersionLookup: boolPtr(true), - Command: intPtr(0), - WebHook: intPtr(0), + Type: test.StringPtr(""), + Icon: test.StringPtr(""), + IconLinkTo: test.StringPtr(""), + HasDeployedVersionLookup: test.BoolPtr(true), + Command: test.IntPtr(0), + WebHook: test.IntPtr(0), Status: &apitype.Status{}}, }, "no commands": { svc: &Service{ Command: command.Slice{}}, want: &apitype.ServiceSummary{ - Type: stringPtr(""), - Icon: stringPtr(""), - IconLinkTo: stringPtr(""), - HasDeployedVersionLookup: boolPtr(false), - Command: intPtr(0), - WebHook: intPtr(0), + Type: test.StringPtr(""), + Icon: test.StringPtr(""), + IconLinkTo: test.StringPtr(""), + HasDeployedVersionLookup: test.BoolPtr(false), + Command: test.IntPtr(0), + WebHook: test.IntPtr(0), Status: &apitype.Status{}}, }, "3 commands": { @@ -313,24 +314,24 @@ func TestService_Summary(t *testing.T) { {"true"}, {"false"}}}, want: &apitype.ServiceSummary{ - Type: stringPtr(""), - Icon: stringPtr(""), - IconLinkTo: stringPtr(""), - HasDeployedVersionLookup: boolPtr(false), - Command: intPtr(3), - WebHook: intPtr(0), + Type: test.StringPtr(""), + Icon: test.StringPtr(""), + IconLinkTo: test.StringPtr(""), + HasDeployedVersionLookup: test.BoolPtr(false), + Command: test.IntPtr(3), + WebHook: test.IntPtr(0), Status: &apitype.Status{}}, }, "0 webhooks": { svc: &Service{ WebHook: webhook.Slice{}}, want: &apitype.ServiceSummary{ - Type: stringPtr(""), - Icon: stringPtr(""), - IconLinkTo: stringPtr(""), - HasDeployedVersionLookup: boolPtr(false), - Command: intPtr(0), - WebHook: intPtr(0), + Type: test.StringPtr(""), + Icon: test.StringPtr(""), + IconLinkTo: test.StringPtr(""), + HasDeployedVersionLookup: test.BoolPtr(false), + Command: test.IntPtr(0), + WebHook: test.IntPtr(0), Status: &apitype.Status{}}, }, "3 webhooks": { @@ -349,12 +350,12 @@ func TestService_Summary(t *testing.T) { "gitlab", "", nil, nil, nil)}}, want: &apitype.ServiceSummary{ - Type: stringPtr(""), - Icon: stringPtr(""), - IconLinkTo: stringPtr(""), - HasDeployedVersionLookup: boolPtr(false), - Command: intPtr(0), - WebHook: intPtr(3), + Type: test.StringPtr(""), + Icon: test.StringPtr(""), + IconLinkTo: test.StringPtr(""), + HasDeployedVersionLookup: test.BoolPtr(false), + Command: test.IntPtr(0), + WebHook: test.IntPtr(3), Status: &apitype.Status{}}, }, "only status": { @@ -367,12 +368,12 @@ func TestService_Summary(t *testing.T) { latestVersionTimestamp: "3-", lastQueried: "4", want: &apitype.ServiceSummary{ - Type: stringPtr(""), - Icon: stringPtr(""), - IconLinkTo: stringPtr(""), - HasDeployedVersionLookup: boolPtr(false), - Command: intPtr(0), - WebHook: intPtr(0), + Type: test.StringPtr(""), + Icon: test.StringPtr(""), + IconLinkTo: test.StringPtr(""), + HasDeployedVersionLookup: test.BoolPtr(false), + Command: test.IntPtr(0), + WebHook: test.IntPtr(0), Status: &apitype.Status{ ApprovedVersion: "1", DeployedVersion: "2", diff --git a/test/main.go b/test/main.go index 2c76e874..30b4658c 100644 --- a/test/main.go +++ b/test/main.go @@ -40,19 +40,13 @@ func CaptureStdout() func() string { } // BoolPtr returns a pointer to the given boolean value -func BoolPtr(val bool) *bool { - return &val -} +func BoolPtr(val bool) *bool { return &val } // IntPtr returns a pointer to the given integer value -func IntPtr(val int) *int { - return &val -} +func IntPtr(val int) *int { return &val } // StringPtr returns a pointer to the given string value -func StringPtr(val string) *string { - return &val -} +func StringPtr(val string) *string { return &val } // UIntPtr returns a pointer to the given unsigned integer value func UIntPtr(val int) *uint { diff --git a/test/secrets.go b/test/secrets.go new file mode 100644 index 00000000..83f789c9 --- /dev/null +++ b/test/secrets.go @@ -0,0 +1,31 @@ +// Copyright [2024] [Argus] +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build unit || integration + +package test + +import ( + "os" +) + +// ShoutrrrGotifyToken returns the token for the Gotify test +func ShoutrrrGotifyToken() (token string) { + token = os.Getenv("ARGUS_TEST_GOTIFY_TOKEN") + if token == "" { + // trunk-ignore(gitleaks/generic-api-key) + token = "AGE-LlHU89Q56uQ" + } + return +} diff --git a/test/secrets_test.go b/test/secrets_test.go new file mode 100644 index 00000000..095cfc27 --- /dev/null +++ b/test/secrets_test.go @@ -0,0 +1,56 @@ +// Copyright [2024] [Argus] +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build unit + +package test + +import ( + "os" + "testing" +) + +func TestShoutrrrGotifyToken(t *testing.T) { + // GIVEN the environment variable ARGUS_TEST_GOTIFY_TOKEN + tests := map[string]struct { + env string + }{ + "empty": {env: ""}, + "set": {env: "test"}, + } + + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + // t.Parallel() - not parallel because we are manipulating the environment + + want := tc.env + if tc.env != "" { + os.Setenv("ARGUS_TEST_GOTIFY_TOKEN", tc.env) + defer os.Unsetenv("ARGUS_TEST_GOTIFY_TOKEN") + } + + // WHEN ShoutrrrGotifyToken is called + token := ShoutrrrGotifyToken() + + // THEN the token should be as expected + if tc.env == "" { + want = token // default token when env is empty + } + if token != want { + t.Errorf("expected %q but got %q", + want, token) + } + }) + } +} diff --git a/testing/commands_test.go b/testing/commands_test.go index 6b84f75f..5cccfd3d 100644 --- a/testing/commands_test.go +++ b/testing/commands_test.go @@ -38,7 +38,7 @@ func TestCommandTest(t *testing.T) { }{ "flag is empty": { flag: "", - stdoutRegex: stringPtr("^$"), + stdoutRegex: test.StringPtr("^$"), slice: service.Slice{ "argus": { ID: "argus", @@ -51,8 +51,8 @@ func TestCommandTest(t *testing.T) { }, "unknown service in flag": { flag: "something", - panicRegex: stringPtr(" could not be found "), - stdoutRegex: stringPtr("should have panic'd before reaching this"), + panicRegex: test.StringPtr(" could not be found "), + stdoutRegex: test.StringPtr("should have panic'd before reaching this"), slice: service.Slice{ "argus": { ID: "argus", @@ -65,7 +65,7 @@ func TestCommandTest(t *testing.T) { }, "known service in flag successful command": { flag: "argus", - stdoutRegex: stringPtr(`Executing 'echo command did run'\s+.*command did run\s+`), + stdoutRegex: test.StringPtr(`Executing 'echo command did run'\s+.*command did run\s+`), slice: service.Slice{ "argus": { ID: "argus", @@ -78,7 +78,7 @@ func TestCommandTest(t *testing.T) { }, "known service in flag failing command": { flag: "argus", - stdoutRegex: stringPtr(`.*Executing 'ls /root'\s+.*exit status [1-9]\s+`), + stdoutRegex: test.StringPtr(`.*Executing 'ls /root'\s+.*exit status [1-9]\s+`), slice: service.Slice{ "argus": { ID: "argus", @@ -91,8 +91,8 @@ func TestCommandTest(t *testing.T) { }, "service with no commands": { flag: "argus", - panicRegex: stringPtr(" does not have any `command` defined"), - stdoutRegex: stringPtr("should have panic'd before reaching this"), + panicRegex: test.StringPtr(" does not have any `command` defined"), + stdoutRegex: test.StringPtr("should have panic'd before reaching this"), slice: service.Slice{ "argus": { ID: "argus"}}, diff --git a/testing/help_test.go b/testing/help_test.go index 98a35a1e..824289af 100644 --- a/testing/help_test.go +++ b/testing/help_test.go @@ -26,12 +26,6 @@ import ( var jLog *util.JLog -func boolPtr(val bool) *bool { - return &val -} -func stringPtr(val string) *string { - return &val -} func TestMain(m *testing.M) { // initialize jLog jLog = util.NewJLog("DEBUG", false) diff --git a/testing/service_test.go b/testing/service_test.go index 4083278f..95bdbbdb 100644 --- a/testing/service_test.go +++ b/testing/service_test.go @@ -46,7 +46,7 @@ func TestServiceTest(t *testing.T) { }{ "flag is empty": { flag: "", - stdoutRegex: stringPtr("^$"), + stdoutRegex: test.StringPtr("^$"), slice: service.Slice{ "argus": { ID: "argus", @@ -58,7 +58,7 @@ func TestServiceTest(t *testing.T) { }, "unknown service": { flag: "test", - panicRegex: stringPtr(`Service "test" could not be found in config.service\sDid you mean one of these\?\s - argus`), + panicRegex: test.StringPtr(`Service "test" could not be found in config.service\sDid you mean one of these\?\s - argus`), slice: service.Slice{ "argus": { ID: "argus", @@ -70,12 +70,12 @@ func TestServiceTest(t *testing.T) { }, "github service": { flag: "argus", - stdoutRegex: stringPtr(`argus\)?, Latest Release - "[0-9]+\.[0-9]+\.[0-9]+"`), + stdoutRegex: test.StringPtr(`argus\)?, Latest Release - "[0-9]+\.[0-9]+\.[0-9]+"`), slice: service.Slice{ "argus": { LatestVersion: *latestver.New( - stringPtr(os.Getenv("GITHUB_TOKEN")), - boolPtr(false), + test.StringPtr(os.Getenv("GITHUB_TOKEN")), + test.BoolPtr(false), nil, opt.New( nil, "0s", nil, @@ -84,19 +84,19 @@ func TestServiceTest(t *testing.T) { "github", "release-argus/Argus", &filter.URLCommandSlice{ - {Type: "regex", Regex: stringPtr("[0-9.]+$")}}, + {Type: "regex", Regex: test.StringPtr("[0-9.]+$")}}, nil, nil, nil)}, }, }, "url service type but github owner/repo url": { flag: "argus", - stdoutRegex: stringPtr("This URL looks to be a GitHub repo, but the service's type is url, not github"), + stdoutRegex: test.StringPtr("This URL looks to be a GitHub repo, but the service's type is url, not github"), slice: service.Slice{ "argus": { ID: "argus", LatestVersion: *latestver.New( nil, - boolPtr(false), + test.BoolPtr(false), nil, opt.New( nil, "0s", nil, @@ -105,18 +105,18 @@ func TestServiceTest(t *testing.T) { "url", "release-argus/Argus", &filter.URLCommandSlice{ - {Type: "regex", Regex: stringPtr("[0-9.]+$")}}, + {Type: "regex", Regex: test.StringPtr("[0-9.]+$")}}, nil, nil, nil)}}, }, "url service": { flag: "argus", - stdoutRegex: stringPtr(`Latest Release - "[0-9]+\.[0-9]+\.[0-9]+"`), + stdoutRegex: test.StringPtr(`Latest Release - "[0-9]+\.[0-9]+\.[0-9]+"`), slice: service.Slice{ "argus": { ID: "argus", LatestVersion: *latestver.New( nil, - boolPtr(false), + test.BoolPtr(false), nil, opt.New( nil, "0s", nil, @@ -125,26 +125,26 @@ func TestServiceTest(t *testing.T) { "url", "https://github.com/release-argus/Argus/releases", &filter.URLCommandSlice{ - {Type: "regex", Regex: stringPtr(`tag/([0-9.]+)"`)}}, + {Type: "regex", Regex: test.StringPtr(`tag/([0-9.]+)"`)}}, nil, nil, nil)}}, }, "service with deployed version lookup": { flag: "argus", - stdoutRegex: stringPtr(`Latest Release - "[0-9]+\.[0-9]+\.[0-9]+"\s.*Deployed version - "[0-9]+\.[0-9]+\.[0-9]+"`), + stdoutRegex: test.StringPtr(`Latest Release - "[0-9]+\.[0-9]+\.[0-9]+"\s.*Deployed version - "[0-9]+\.[0-9]+\.[0-9]+"`), slice: service.Slice{ "argus": { ID: "argus", LatestVersion: *latestver.New( nil, - boolPtr(false), + test.BoolPtr(false), nil, nil, nil, nil, "url", "https://github.com/release-argus/Argus/releases", &filter.URLCommandSlice{ - {Type: "regex", Regex: stringPtr(`tag/([0-9.]+)"`)}}, + {Type: "regex", Regex: test.StringPtr(`tag/([0-9.]+)"`)}}, nil, nil, nil), DeployedVersionLookup: deployedver.New( - boolPtr(true), + test.BoolPtr(true), nil, nil, "version", nil, "", nil, @@ -152,7 +152,7 @@ func TestServiceTest(t *testing.T) { "https://release-argus.io/demo/api/v1/version", nil, nil), Options: *opt.New( - nil, "0s", boolPtr(true), + nil, "0s", test.BoolPtr(true), nil, nil)}}, }, } diff --git a/testing/shoutrrr_test.go b/testing/shoutrrr_test.go index 8c4f6529..3fe3d834 100644 --- a/testing/shoutrrr_test.go +++ b/testing/shoutrrr_test.go @@ -123,7 +123,7 @@ func TestFindShoutrrr(t *testing.T) { }{ "empty search with only Service notifiers": { flag: "", - panicRegex: stringPtr(`could not be found.*\s+.*one of these?.*\s - bar\s - baz\s - foo\s$`), + panicRegex: test.StringPtr(`could not be found.*\s+.*one of these?.*\s - bar\s - baz\s - foo\s$`), cfg: &config.Config{ Service: service.Slice{ "argus": { @@ -134,7 +134,7 @@ func TestFindShoutrrr(t *testing.T) { }, "empty search with only Root notifiers": { flag: "", - panicRegex: stringPtr(`could not be found.*\s+.*one of these?.*\s - bar\s - baz\s - foo\s$`), + panicRegex: test.StringPtr(`could not be found.*\s+.*one of these?.*\s - bar\s - baz\s - foo\s$`), cfg: &config.Config{ Notify: shoutrrr.SliceDefaults{ "foo": {}, @@ -143,7 +143,7 @@ func TestFindShoutrrr(t *testing.T) { }, "empty search with Root notifiers and Service notifiers and no duplicates": { flag: "", - panicRegex: stringPtr(`could not be found.*\s+.*one of these?.*\s - bar\s - baz\s - foo\s$`), + panicRegex: test.StringPtr(`could not be found.*\s+.*one of these?.*\s - bar\s - baz\s - foo\s$`), cfg: &config.Config{ Notify: shoutrrr.SliceDefaults{ "foo": {}, @@ -158,7 +158,7 @@ func TestFindShoutrrr(t *testing.T) { }, "empty search with Root notifiers and Service notifiers and duplicates": { flag: "", - panicRegex: stringPtr(`could not be found.*\s+.*one of these?.*\s - bar\s - baz\s - foo\s - shazam\s$`), + panicRegex: test.StringPtr(`could not be found.*\s+.*one of these?.*\s - bar\s - baz\s - foo\s - shazam\s$`), cfg: &config.Config{ Service: service.Slice{ "argus": { @@ -170,7 +170,7 @@ func TestFindShoutrrr(t *testing.T) { }, "matching search of notifier in Root": { flag: "bosh", - stdoutRegex: stringPtr("^$"), + stdoutRegex: test.StringPtr("^$"), cfg: &config.Config{ Service: service.Slice{ "argus": { @@ -183,11 +183,11 @@ func TestFindShoutrrr(t *testing.T) { &map[string]string{ "host": "example.com", "token": "example"})}}, - foundInRoot: boolPtr(true), + foundInRoot: test.BoolPtr(true), }, "matching search of notifier in Service": { flag: "baz", - stdoutRegex: stringPtr("^$"), + stdoutRegex: test.StringPtr("^$"), cfg: &config.Config{ Service: service.Slice{ "argus": { @@ -200,11 +200,11 @@ func TestFindShoutrrr(t *testing.T) { "host": "example.com", "token": "example"}, nil, nil, nil)}}}}, - foundInRoot: boolPtr(false), + foundInRoot: test.BoolPtr(false), }, "matching search of notifier in Root and a Service": { flag: "bar", - stdoutRegex: stringPtr("^$"), + stdoutRegex: test.StringPtr("^$"), cfg: &config.Config{ Service: service.Slice{ "argus": { @@ -225,7 +225,7 @@ func TestFindShoutrrr(t *testing.T) { &map[string]string{ "host": "example.com", "token": "example"})}}, - foundInRoot: boolPtr(false), + foundInRoot: test.BoolPtr(false), }, "matching search of Service notifier with incomplete config filled by Defaults": { flag: "bar", @@ -256,7 +256,7 @@ func TestFindShoutrrr(t *testing.T) { &map[string]string{ "toaddresses": "me@you.com"}, nil)}}}, - foundInRoot: boolPtr(false), + foundInRoot: test.BoolPtr(false), }, "matching search of Service notifier with incomplete config filled by Root": { flag: "bar", @@ -286,7 +286,7 @@ func TestFindShoutrrr(t *testing.T) { &map[string]string{ "toaddresses": "me@you.com"}, nil)}}, - foundInRoot: boolPtr(false), + foundInRoot: test.BoolPtr(false), }, "matching search of Service notifier with incomplete config filled by Root and Defaults": { flag: "bosh", @@ -323,11 +323,11 @@ func TestFindShoutrrr(t *testing.T) { &map[string]string{ "toaddresses": "me@you.com"}, nil)}}}, - foundInRoot: boolPtr(false), + foundInRoot: test.BoolPtr(false), }, "matching search of Root notifier with invalid config": { flag: "bosh", - panicRegex: stringPtr(`^notify:\s bosh:\s params:\s toaddresses: `), + panicRegex: test.StringPtr(`^notify:\s bosh:\s params:\s toaddresses: `), cfg: &config.Config{ Service: service.Slice{ "argus": { @@ -343,7 +343,7 @@ func TestFindShoutrrr(t *testing.T) { "fromaddress": "test@release-argus.io"}, &map[string]string{ "host": "example.com"})}}, - foundInRoot: boolPtr(true), + foundInRoot: test.BoolPtr(true), }, "matching search of Root notifier with incomplete config filled by Defaults": { flag: "bosh", @@ -375,7 +375,7 @@ func TestFindShoutrrr(t *testing.T) { &map[string]string{ "toaddresses": "me@you.com"}, nil)}}}, - foundInRoot: boolPtr(true), + foundInRoot: test.BoolPtr(true), }, } @@ -462,7 +462,7 @@ func TestNotifyTest(t *testing.T) { panicRegex *string }{ "empty flag": {flag: "", - stdoutRegex: stringPtr("^$"), + stdoutRegex: test.StringPtr("^$"), slice: service.Slice{ "argus": { Notify: shoutrrr.Slice{ @@ -472,7 +472,7 @@ func TestNotifyTest(t *testing.T) { }, }}}, "unknown Notifier": {flag: "something", - panicRegex: stringPtr("Notifier.* could not be found"), + panicRegex: test.StringPtr("Notifier.* could not be found"), slice: service.Slice{ "argus": { Notify: shoutrrr.Slice{ @@ -483,7 +483,7 @@ func TestNotifyTest(t *testing.T) { }}}, "known Service Notifier with invalid Gotify token": { flag: "bar", - panicRegex: stringPtr(`Message failed to send with "bar" config\s+invalid gotify token`), + panicRegex: test.StringPtr(`Message failed to send with "bar" config\s+invalid gotify token`), slice: service.Slice{ "argus": { Notify: shoutrrr.Slice{ @@ -504,7 +504,7 @@ func TestNotifyTest(t *testing.T) { }, "valid Gotify token": { flag: "bar", - panicRegex: stringPtr(`HTTP 404 Not Found`), + panicRegex: test.StringPtr(`HTTP 404 Not Found`), slice: service.Slice{ "argus": { Notify: shoutrrr.Slice{ @@ -525,7 +525,7 @@ func TestNotifyTest(t *testing.T) { }, "shoutrrr from Root": { flag: "baz", - panicRegex: stringPtr(`HTTP 404 Not Found`), + panicRegex: test.StringPtr(`HTTP 404 Not Found`), slice: service.Slice{}, rootSlice: shoutrrr.SliceDefaults{ "baz": shoutrrr.NewDefaults( diff --git a/util/help_test.go b/util/help_test.go index a7322737..e3f37379 100644 --- a/util/help_test.go +++ b/util/help_test.go @@ -16,11 +16,6 @@ package util -func boolPtr(val bool) *bool { return &val } -func intPtr(val int) *int { return &val } -func stringPtr(val string) *string { return &val } -func nilMap() map[string]string { return nil } - func testServiceInfo() ServiceInfo { return ServiceInfo{ ID: "something", diff --git a/util/log_test.go b/util/log_test.go index ac15a6d9..8d599c16 100644 --- a/util/log_test.go +++ b/util/log_test.go @@ -83,7 +83,7 @@ func TestSetLevel(t *testing.T) { "lower-case verbose": {level: "verbose"}, "mixed-case vERbOse": {level: "vERbOse"}, "invalid level PINEAPPLE": {level: "PINEAPPLE", - panicRegex: stringPtr(`not a valid log\.level`)}} + panicRegex: test.StringPtr(`not a valid log\.level`)}} for name, tc := range tests { t.Run(name, func(t *testing.T) { @@ -529,7 +529,7 @@ func TestJLog_Verbose(t *testing.T) { level: "DEBUG", timestamps: false, otherCondition: false, shouldPrint: false}, "limits VERBOSE message length": { level: "VERBOSE", timestamps: false, otherCondition: true, shouldPrint: true, - customMsg: stringPtr(strings.Repeat("a", 9999)), expectedLength: 1000}, + customMsg: test.StringPtr(strings.Repeat("a", 9999)), expectedLength: 1000}, } for name, tc := range tests { @@ -627,7 +627,7 @@ func TestJLog_Debug(t *testing.T) { level: "DEBUG", timestamps: false, otherCondition: false, shouldPrint: false}, "limits DEBUG message length": { level: "DEBUG", timestamps: false, otherCondition: true, shouldPrint: true, - customMsg: stringPtr(strings.Repeat("a", 9999)), expectedLength: 1000}, + customMsg: test.StringPtr(strings.Repeat("a", 9999)), expectedLength: 1000}, } for name, tc := range tests { diff --git a/util/regex_test.go b/util/regex_test.go index 273474b8..f51c2d86 100644 --- a/util/regex_test.go +++ b/util/regex_test.go @@ -19,6 +19,8 @@ package util import ( "regexp" "testing" + + "github.com/release-argus/Argus/test" ) func TestRegexCheck(t *testing.T) { @@ -93,25 +95,25 @@ func TestRegexTemplate(t *testing.T) { "datetime template": { text: "2024-01-01T16-36-33Z", regex: `([\d-]+)T(\d+)-(\d+)-(\d+)Z`, - template: stringPtr("$1T$2:$3:$4Z"), + template: test.StringPtr("$1T$2:$3:$4Z"), want: "2024-01-01T16:36:33Z", }, "template with 10+ matches": { text: "abcdefghijklmnopqrstuvwxyz", regex: `([a-z])([a-z])([a-z])([a-z])([a-z]{2})([a-z])([a-z])([a-z])([a-z])([a-z])([a-z])`, - template: stringPtr("$1_$2_$3_$4_$5_$6_$7_$8_$9_$10_$11"), + template: test.StringPtr("$1_$2_$3_$4_$5_$6_$7_$8_$9_$10_$11"), want: "a_b_c_d_ef_g_h_i_j_k_l", }, "template with placeholder out of range": { text: "abc123-def456-ghi789", regex: `([a-z]+)(\d+)`, - template: stringPtr("$1$4-$10"), + template: test.StringPtr("$1$4-$10"), want: "abc$4-abc0", }, "template with all placeholders out of range": { text: "abc123-def456-ghi789", regex: `([a-z]+)(\d+)`, - template: stringPtr("$4$5"), + template: test.StringPtr("$4$5"), want: "$4$5", }, "no template": { diff --git a/util/template_test.go b/util/template_test.go index 8c09218b..5d305847 100644 --- a/util/template_test.go +++ b/util/template_test.go @@ -20,6 +20,8 @@ import ( "fmt" "regexp" "testing" + + "github.com/release-argus/Argus/test" ) func TestTemplate_String(t *testing.T) { @@ -38,7 +40,7 @@ func TestTemplate_String(t *testing.T) { want: "-something-example.com-other.com-NEW"}, "invalid jinja template panic": { tmpl: "-{% 'a' == 'a' %}{{ service_id }}{% endif %}-{{ service_url }}-{{ web_url }}-{{ version }}", - panicRegex: stringPtr("Tag name must be an identifier")}, + panicRegex: test.StringPtr("Tag name must be an identifier")}, } for name, tc := range tests { diff --git a/util/util_test.go b/util/util_test.go index 71bc0d99..50dfa246 100644 --- a/util/util_test.go +++ b/util/util_test.go @@ -71,7 +71,7 @@ func TestEvalNilPtr(t *testing.T) { ptr: nil, nilStr: "bar", want: "bar"}, "non-nil *string": { - ptr: stringPtr("foo"), nilStr: "bar", + ptr: test.StringPtr("foo"), nilStr: "bar", want: "foo"}, } @@ -102,7 +102,7 @@ func TestPtrOrValueToPtr(t *testing.T) { a: nil, b: "bar", want: "bar"}, "non-nil `a` pointer": { - a: stringPtr("foo"), b: "bar", + a: test.StringPtr("foo"), b: "bar", want: "foo"}, } @@ -133,8 +133,8 @@ func TestValueIfNotNil(t *testing.T) { check: nil, value: "foo", want: nil}, "non-nil `check` pointer": { - check: stringPtr("foo"), value: "bar", - want: stringPtr("bar")}, + check: test.StringPtr("foo"), value: "bar", + want: test.StringPtr("bar")}, } for name, tc := range tests { @@ -206,7 +206,7 @@ func TestDefaultIfNil(t *testing.T) { check: nil, want: ""}, "non-nil `check` pointer": { - check: stringPtr("foo"), + check: test.StringPtr("foo"), want: "foo"}, } @@ -250,15 +250,15 @@ func TestFirstNonNilPtr(t *testing.T) { nil, nil, nil, - stringPtr("bar")}, + test.StringPtr("bar")}, wantIndex: 3, }, "2 non-nil pointers": { pointers: []*string{ - stringPtr("foo"), + test.StringPtr("foo"), nil, nil, - stringPtr("bar")}, + test.StringPtr("bar")}, wantIndex: 0, }, } @@ -313,7 +313,7 @@ func TestFirstNonNilPtrWithEnv(t *testing.T) { nil, nil, nil, - stringPtr("bar")}, + test.StringPtr("bar")}, wantIndex: 3, }, "1 non-nil pointer (env var)": { @@ -322,7 +322,7 @@ func TestFirstNonNilPtrWithEnv(t *testing.T) { nil, nil, nil, - stringPtr("${TESTFIRSTNONNILPTRWITHENV_ONE}")}, + test.StringPtr("${TESTFIRSTNONNILPTRWITHENV_ONE}")}, wantIndex: 3, diffAddress: true, wantText: "bar", @@ -333,7 +333,7 @@ func TestFirstNonNilPtrWithEnv(t *testing.T) { nil, nil, nil, - stringPtr("foo${TESTFIRSTNONNILPTRWITHENV_TWO}")}, + test.StringPtr("foo${TESTFIRSTNONNILPTRWITHENV_TWO}")}, wantIndex: 3, diffAddress: true, wantText: "foobar", @@ -344,7 +344,7 @@ func TestFirstNonNilPtrWithEnv(t *testing.T) { nil, nil, nil, - stringPtr("${TESTFIRSTNONNILPTRWITHENV_THREE}")}, + test.StringPtr("${TESTFIRSTNONNILPTRWITHENV_THREE}")}, wantIndex: 3, diffAddress: true, wantText: "", @@ -354,17 +354,17 @@ func TestFirstNonNilPtrWithEnv(t *testing.T) { nil, nil, nil, - stringPtr("${TESTFIRSTNONNILPTRWITHENV_UNSET}")}, + test.StringPtr("${TESTFIRSTNONNILPTRWITHENV_UNSET}")}, wantIndex: 3, diffAddress: false, wantText: "${TESTFIRSTNONNILPTRWITHENV_UNSET}", }, "2 non-nil pointers": { pointers: []*string{ - stringPtr("foo"), + test.StringPtr("foo"), nil, nil, - stringPtr("bar")}, + test.StringPtr("bar")}, wantIndex: 0, }, } @@ -664,7 +664,7 @@ func TestPrintlnIfNotNil(t *testing.T) { "nil pointer": { element: nil, didPrint: false}, "non-nil pointer": { - element: stringPtr("foo"), didPrint: true}, + element: test.StringPtr("foo"), didPrint: true}, } for name, tc := range tests { @@ -703,7 +703,7 @@ func TestPrintlnIfNil(t *testing.T) { "nil pointer": { element: nil, didPrint: true}, "non-nil pointer": { - element: stringPtr("foo"), didPrint: false}, + element: test.StringPtr("foo"), didPrint: false}, } for name, tc := range tests { @@ -743,7 +743,7 @@ func TestDefaultOrValue(t *testing.T) { "nil pointer": { element: nil, want: ""}, "non-nil pointer": { - element: stringPtr("foo"), value: "bar", want: "bar"}, + element: test.StringPtr("foo"), value: "bar", want: "bar"}, } for name, tc := range tests { @@ -773,19 +773,19 @@ func TestPtrValueOrValue(t *testing.T) { ptr: (*string)(nil), value: "argus", want: "argus"}, "non-nil string pointer": { - ptr: stringPtr("foo"), + ptr: test.StringPtr("foo"), value: "bar", want: "foo"}, "nil bool pointer": { ptr: (*bool)(nil), value: false, want: false}, "non-nil bool pointer": { - ptr: boolPtr(true), + ptr: test.BoolPtr(true), value: false, want: true}, "nil int pointer": { ptr: (*int)(nil), value: 1, want: 1}, "non-nil int pointer": { - ptr: intPtr(3), + ptr: test.IntPtr(3), value: 2, want: 3}, } @@ -1103,7 +1103,7 @@ func TestInitMap(t *testing.T) { input map[string]string }{ "nil map": { - input: nilMap(), + input: nil, }, "empty map": { input: map[string]string{}, @@ -1216,8 +1216,8 @@ func TestMergeMaps(t *testing.T) { want: map[string]string{}, }, "nil maps": { - base: nilMap(), - overrides: nilMap(), + base: nil, + overrides: nil, want: map[string]string{}, }, "empty base map": { @@ -1230,7 +1230,7 @@ func TestMergeMaps(t *testing.T) { "foo": "bar"}, }, "nil base map": { - base: nilMap(), + base: nil, overrides: map[string]string{ "test": "123", "foo": "bar"}, @@ -1251,7 +1251,7 @@ func TestMergeMaps(t *testing.T) { base: map[string]string{ "test": "123", "foo": "bar"}, - overrides: nilMap(), + overrides: nil, want: map[string]string{ "test": "123", "foo": "bar"}, @@ -1498,9 +1498,9 @@ func TestStringToBoolPtr(t *testing.T) { want *bool }{ "'true' gives true": { - input: "true", want: boolPtr(true)}, + input: "true", want: test.BoolPtr(true)}, "'false' gives false": { - input: "false", want: boolPtr(false)}, + input: "false", want: test.BoolPtr(false)}, "'' gives nil": { input: "", want: nil}, } @@ -1541,11 +1541,11 @@ func TestEnvReplaceFunc(t *testing.T) { want: strBase, }, "empty env var": { - envVar: stringPtr(""), + envVar: test.StringPtr(""), want: "", }, "non-empty env var": { - envVar: stringPtr("bar"), + envVar: test.StringPtr("bar"), want: "bar", }, } @@ -1925,7 +1925,7 @@ func TestStringToPointer(t *testing.T) { want: nil}, "non-empty string": { input: "test", - want: stringPtr("test")}, + want: test.StringPtr("test")}, } for name, tc := range tests { diff --git a/web/api/types/argus_test.go b/web/api/types/argus_test.go index b27053c7..50d1fac9 100644 --- a/web/api/types/argus_test.go +++ b/web/api/types/argus_test.go @@ -21,6 +21,7 @@ import ( "strings" "testing" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) @@ -341,9 +342,9 @@ func TestWebHook_Censor(t *testing.T) { }, "secret": { webhook: &WebHook{ - Secret: stringPtr("shazam")}, + Secret: test.StringPtr("shazam")}, want: &WebHook{ - Secret: stringPtr("")}, + Secret: test.StringPtr("")}, }, "custom_headers": { webhook: &WebHook{ @@ -357,12 +358,12 @@ func TestWebHook_Censor(t *testing.T) { }, "all": { webhook: &WebHook{ - Secret: stringPtr("shazam"), + Secret: test.StringPtr("shazam"), CustomHeaders: &[]Header{ {Key: "X-Header", Value: "something"}, {Key: "X-Bing", Value: "Bam"}}}, want: &WebHook{ - Secret: stringPtr(""), + Secret: test.StringPtr(""), CustomHeaders: &[]Header{ {Key: "X-Header", Value: ""}, {Key: "X-Bing", Value: ""}}}, @@ -413,27 +414,27 @@ func TestWebHookSlice_Flatten(t *testing.T) { }, "webhooks ordered": { webhook: &WebHookSlice{ - "alpha": &WebHook{URL: stringPtr("https://example.com")}, - "bravo": &WebHook{URL: stringPtr("https://example.com/other")}}, + "alpha": &WebHook{URL: test.StringPtr("https://example.com")}, + "bravo": &WebHook{URL: test.StringPtr("https://example.com/other")}}, want: &[]*WebHook{ - {ID: "alpha", URL: stringPtr("https://example.com")}, - {ID: "bravo", URL: stringPtr("https://example.com/other")}}, + {ID: "alpha", URL: test.StringPtr("https://example.com")}, + {ID: "bravo", URL: test.StringPtr("https://example.com/other")}}, }, "webhooks ordered and censored": { webhook: &WebHookSlice{ "alpha": &WebHook{ - URL: stringPtr("https://example.com"), - Secret: stringPtr("foo")}, + URL: test.StringPtr("https://example.com"), + Secret: test.StringPtr("foo")}, "bravo": &WebHook{ - URL: stringPtr("https://example.com/other"), - Secret: stringPtr("bar")}}, + URL: test.StringPtr("https://example.com/other"), + Secret: test.StringPtr("bar")}}, want: &[]*WebHook{ {ID: "alpha", - URL: stringPtr("https://example.com"), - Secret: stringPtr("")}, + URL: test.StringPtr("https://example.com"), + Secret: test.StringPtr("")}, {ID: "bravo", - URL: stringPtr("https://example.com/other"), - Secret: stringPtr("")}}, + URL: test.StringPtr("https://example.com/other"), + Secret: test.StringPtr("")}}, }, } @@ -476,9 +477,9 @@ func TestServiceSummary_String(t *testing.T) { "some": { summary: &ServiceSummary{ ID: "foo", - Type: stringPtr("github"), - Command: intPtr(1), - WebHook: intPtr(2)}, + Type: test.StringPtr("github"), + Command: test.IntPtr(1), + WebHook: test.IntPtr(2)}, want: ` { "id": "foo", @@ -490,15 +491,15 @@ func TestServiceSummary_String(t *testing.T) { "full": { summary: &ServiceSummary{ ID: "bar", - Active: boolPtr(true), - Comment: stringPtr("test"), - Type: stringPtr("gitlab"), + Active: test.BoolPtr(true), + Comment: test.StringPtr("test"), + Type: test.StringPtr("gitlab"), WebURL: "http://example.com", - Icon: stringPtr("https://example.com/icon.png"), - IconLinkTo: stringPtr("https://release-argus.io"), - HasDeployedVersionLookup: boolPtr(true), - Command: intPtr(2), - WebHook: intPtr(1), + Icon: test.StringPtr("https://example.com/icon.png"), + IconLinkTo: test.StringPtr("https://release-argus.io"), + HasDeployedVersionLookup: test.BoolPtr(true), + Command: test.IntPtr(2), + WebHook: test.IntPtr(1), Status: &Status{ ApprovedVersion: "1.2.3"}}, want: ` @@ -524,7 +525,7 @@ func TestServiceSummary_String(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - tc.want = trimJSON(tc.want) + tc.want = test.TrimJSON(tc.want) // WHEN the Summary is stringified with String got := tc.summary.String() @@ -569,78 +570,78 @@ func TestServiceSummary_RemoveUnchanged(t *testing.T) { }, "same active": { old: &ServiceSummary{ - Active: boolPtr(false)}, + Active: test.BoolPtr(false)}, new: &ServiceSummary{ - Active: boolPtr(false)}, + Active: test.BoolPtr(false)}, want: &ServiceSummary{}, }, "different active": { old: &ServiceSummary{ - Active: boolPtr(true)}, + Active: test.BoolPtr(true)}, new: &ServiceSummary{ - Active: boolPtr(false)}, + Active: test.BoolPtr(false)}, want: &ServiceSummary{ - Active: boolPtr(false)}, + Active: test.BoolPtr(false)}, }, "same type": { old: &ServiceSummary{ - Type: stringPtr("github")}, + Type: test.StringPtr("github")}, new: &ServiceSummary{ - Type: stringPtr("github")}, + Type: test.StringPtr("github")}, want: &ServiceSummary{}, }, "different type": { old: &ServiceSummary{ - Type: stringPtr("github")}, + Type: test.StringPtr("github")}, new: &ServiceSummary{ - Type: stringPtr("gitlab")}, + Type: test.StringPtr("gitlab")}, want: &ServiceSummary{ - Type: stringPtr("gitlab")}, + Type: test.StringPtr("gitlab")}, }, "same icon": { old: &ServiceSummary{ - Icon: stringPtr("https://example.com/icon.png")}, + Icon: test.StringPtr("https://example.com/icon.png")}, new: &ServiceSummary{ - Icon: stringPtr("https://example.com/icon.png")}, + Icon: test.StringPtr("https://example.com/icon.png")}, want: &ServiceSummary{}, }, "different icon": { old: &ServiceSummary{ - Icon: stringPtr("https://example.com/icon.png")}, + Icon: test.StringPtr("https://example.com/icon.png")}, new: &ServiceSummary{ - Icon: stringPtr("https://example.com/icon2.png")}, + Icon: test.StringPtr("https://example.com/icon2.png")}, want: &ServiceSummary{ - Icon: stringPtr("https://example.com/icon2.png")}, + Icon: test.StringPtr("https://example.com/icon2.png")}, }, "same icon_link_to": { old: &ServiceSummary{ - IconLinkTo: stringPtr("https://release-argus.io")}, + IconLinkTo: test.StringPtr("https://release-argus.io")}, new: &ServiceSummary{ - IconLinkTo: stringPtr("https://release-argus.io")}, + IconLinkTo: test.StringPtr("https://release-argus.io")}, want: &ServiceSummary{}, }, "different icon_link_to": { old: &ServiceSummary{ - IconLinkTo: stringPtr("https://release-argus.io")}, + IconLinkTo: test.StringPtr("https://release-argus.io")}, new: &ServiceSummary{ - IconLinkTo: stringPtr("https://release-argus.io/other")}, + IconLinkTo: test.StringPtr("https://release-argus.io/other")}, want: &ServiceSummary{ - IconLinkTo: stringPtr("https://release-argus.io/other")}, + IconLinkTo: test.StringPtr("https://release-argus.io/other")}, }, "same has_deployed_version_lookup": { old: &ServiceSummary{ - HasDeployedVersionLookup: boolPtr(true)}, + HasDeployedVersionLookup: test.BoolPtr(true)}, new: &ServiceSummary{ - HasDeployedVersionLookup: boolPtr(true)}, + HasDeployedVersionLookup: test.BoolPtr(true)}, want: &ServiceSummary{}, }, "different has_deployed_version_lookup": { old: &ServiceSummary{ - HasDeployedVersionLookup: boolPtr(true)}, + HasDeployedVersionLookup: test.BoolPtr(true)}, new: &ServiceSummary{ - HasDeployedVersionLookup: boolPtr(false)}, + HasDeployedVersionLookup: test.BoolPtr(false)}, want: &ServiceSummary{ - HasDeployedVersionLookup: boolPtr(false)}, + HasDeployedVersionLookup: test.BoolPtr(false)}, }, "same approved_version": { old: &ServiceSummary{ @@ -732,17 +733,17 @@ func TestServiceSummary_RemoveUnchanged(t *testing.T) { }, "mmultiple differences": { old: &ServiceSummary{ - IconLinkTo: stringPtr("https://release-argus.io"), + IconLinkTo: test.StringPtr("https://release-argus.io"), Status: &Status{ DeployedVersion: "1.2.3", DeployedVersionTimestamp: "2020-01-01T00:00:00Z"}}, new: &ServiceSummary{ - IconLinkTo: stringPtr("https://release-argus.io/other"), + IconLinkTo: test.StringPtr("https://release-argus.io/other"), Status: &Status{ DeployedVersion: "4.5.6", DeployedVersionTimestamp: "2020-02-02T00:00:00Z"}}, want: &ServiceSummary{ - IconLinkTo: stringPtr("https://release-argus.io/other"), + IconLinkTo: test.StringPtr("https://release-argus.io/other"), Status: &Status{ DeployedVersion: "4.5.6", DeployedVersionTimestamp: "2020-02-02T00:00:00Z"}}, @@ -815,7 +816,7 @@ func TestStatus_String(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - tc.want = trimJSON(tc.want) + tc.want = test.TrimJSON(tc.want) // WHEN the Status is stringified with String got := tc.status.String() @@ -847,22 +848,22 @@ func TestWebHook_String(t *testing.T) { webhook: &WebHook{ ServiceID: "something", ID: "foobar", - Type: stringPtr("url"), - URL: stringPtr("https://release-argus.io"), - AllowInvalidCerts: boolPtr(true), - Secret: stringPtr("secret"), + Type: test.StringPtr("url"), + URL: test.StringPtr("https://release-argus.io"), + AllowInvalidCerts: test.BoolPtr(true), + Secret: test.StringPtr("secret"), CustomHeaders: &[]Header{ {Key: "X-Header", Value: "bosh"}}, - DesiredStatusCode: intPtr(200), + DesiredStatusCode: test.IntPtr(200), Delay: "1h", - MaxTries: uintPtr(7), - SilentFails: boolPtr(false), + MaxTries: test.UIntPtr(7), + SilentFails: test.BoolPtr(false), }, want: ` { "name": "foobar", "type": "url", - "url": "https: //release-argus.io", + "url": "https://release-argus.io", "allow_invalid_certs": true, "secret": "secret", "custom_headers": [{"key": "X-Header","value": "bosh"}], @@ -882,9 +883,9 @@ func TestWebHook_String(t *testing.T) { got := tc.webhook.String() // THEN the result is as expected - tc.want = trimJSON(tc.want) + tc.want = test.TrimJSON(tc.want) if got != tc.want { - t.Errorf("got: %q, want: %q", + t.Errorf("mismatch\ngot: %q\nwant: %q", got, tc.want) } }) @@ -909,16 +910,16 @@ func TestWebHookSlice_String(t *testing.T) { slice: &WebHookSlice{ "0": {ServiceID: "something", ID: "foobar", - Type: stringPtr("url"), - URL: stringPtr("https://release-argus.io"), - AllowInvalidCerts: boolPtr(true), - Secret: stringPtr("secret"), + Type: test.StringPtr("url"), + URL: test.StringPtr("https://release-argus.io"), + AllowInvalidCerts: test.BoolPtr(true), + Secret: test.StringPtr("secret"), CustomHeaders: &[]Header{ {Key: "X-Header", Value: "bosh"}}, - DesiredStatusCode: intPtr(200), + DesiredStatusCode: test.IntPtr(200), Delay: "1h", - MaxTries: uintPtr(7), - SilentFails: boolPtr(false)}, + MaxTries: test.UIntPtr(7), + SilentFails: test.BoolPtr(false)}, }, want: ` { @@ -938,9 +939,9 @@ func TestWebHookSlice_String(t *testing.T) { }, "multiple webhooks": { slice: &WebHookSlice{ - "0": {URL: stringPtr("bish")}, - "1": {Secret: stringPtr("bash")}, - "2": {Type: stringPtr("github")}}, + "0": {URL: test.StringPtr("bish")}, + "1": {Secret: test.StringPtr("bash")}, + "2": {Type: test.StringPtr("github")}}, want: ` { "0": {"url": "bish"}, @@ -958,7 +959,7 @@ func TestWebHookSlice_String(t *testing.T) { got := tc.slice.String() // THEN the result is as expected - tc.want = trimJSON(tc.want) + tc.want = test.TrimJSON(tc.want) if got != tc.want { t.Errorf("got: %q\nwant: %q", got, tc.want) @@ -1048,7 +1049,7 @@ func TestNotifySlice_String(t *testing.T) { got := tc.slice.String() // THEN the result is as expected - tc.want = trimJSON(tc.want) + tc.want = test.TrimJSON(tc.want) if got != tc.want { t.Errorf("got:\n%q\nwant:\n%q", got, tc.want) @@ -1074,7 +1075,7 @@ func TestDeployedVersionLookup_String(t *testing.T) { "all fields": { dvl: &DeployedVersionLookup{ URL: "https://release-argus.io", - AllowInvalidCerts: boolPtr(false), + AllowInvalidCerts: test.BoolPtr(false), BasicAuth: &BasicAuth{ Username: "user", Password: "pass"}, @@ -1109,7 +1110,7 @@ func TestDeployedVersionLookup_String(t *testing.T) { got := tc.dvl.String() // THEN the result is as expected - tc.want = trimJSON(tc.want) + tc.want = test.TrimJSON(tc.want) if got != tc.want { t.Errorf("got:\n%q\nwant:\n%q", got, tc.want) @@ -1134,9 +1135,9 @@ func TestURLCommandSlice_String(t *testing.T) { }, "one of each type": { slice: &URLCommandSlice{ - {Type: "regex", Regex: stringPtr("bam")}, - {Type: "replace", Old: stringPtr("want-rid"), New: stringPtr("replacement")}, - {Type: "split", Text: stringPtr("split on me"), Index: 5}, + {Type: "regex", Regex: test.StringPtr("bam")}, + {Type: "replace", Old: test.StringPtr("want-rid"), New: test.StringPtr("replacement")}, + {Type: "split", Text: test.StringPtr("split on me"), Index: 5}, }, want: ` [ @@ -1155,7 +1156,7 @@ func TestURLCommandSlice_String(t *testing.T) { got := tc.slice.String() // THEN the result is as expected - tc.want = trimJSON(tc.want) + tc.want = test.TrimJSON(tc.want) if got != tc.want { t.Errorf("got:\n%q\nwant:\n%q", got, tc.want) @@ -1188,7 +1189,7 @@ func TestDefaults_String(t *testing.T) { URLFields: map[string]string{ "url": "https://gotify.example.com"}}}, WebHook: WebHook{ - Secret: stringPtr("bar")}}, + Secret: test.StringPtr("bar")}}, want: ` { "service": { @@ -1212,7 +1213,7 @@ func TestDefaults_String(t *testing.T) { got := tc.dflts.String() // THEN the result is as expected - tc.want = trimJSON(tc.want) + tc.want = test.TrimJSON(tc.want) if got != tc.want { t.Errorf("got:\n%q\nwant:\n%q", got, tc.want) @@ -1271,12 +1272,12 @@ func TestLatestVersion_String(t *testing.T) { Type: "github", URL: "release-argus/argus", AccessToken: "", - AllowInvalidCerts: boolPtr(true), - UsePreRelease: boolPtr(false), + AllowInvalidCerts: test.BoolPtr(true), + UsePreRelease: test.BoolPtr(false), URLCommands: &URLCommandSlice{ - {Type: "replace", Old: stringPtr("this"), New: stringPtr("withThis")}, - {Type: "split", Text: stringPtr("splitThis"), Index: 8}, - {Type: "regex", Regex: stringPtr("([0-9.]+)")}}, + {Type: "replace", Old: test.StringPtr("this"), New: test.StringPtr("withThis")}, + {Type: "split", Text: test.StringPtr("splitThis"), Index: 8}, + {Type: "regex", Regex: test.StringPtr("([0-9.]+)")}}, Require: &LatestVersionRequire{ RegexContent: ".*"}}, want: ` @@ -1301,7 +1302,7 @@ func TestLatestVersion_String(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - tc.want = trimJSON(tc.want) + tc.want = test.TrimJSON(tc.want) // WHEN the LatestVersion is stringified with String got := tc.input.String() @@ -1358,7 +1359,7 @@ func TestLatestVersionRequireDefaults_String(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - tc.want = trimJSON(tc.want) + tc.want = test.TrimJSON(tc.want) // WHEN the LatestVersionRequireDefaults are stringified with String got := tc.lvrd.String() @@ -1414,7 +1415,7 @@ func TestLatestVersionRequire_String(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - tc.want = trimJSON(tc.want) + tc.want = test.TrimJSON(tc.want) // WHEN the LatestVersionRequire is stringified with String got := tc.input.String() diff --git a/web/api/types/help_test.go b/web/api/types/help_test.go index e385bc32..9f2e1df2 100644 --- a/web/api/types/help_test.go +++ b/web/api/types/help_test.go @@ -16,21 +16,6 @@ package apitype -import "strings" - -func boolPtr(val bool) *bool { - return &val -} -func intPtr(val int) *int { - return &val -} -func uintPtr(val uint) *uint { - return &val -} -func stringPtr(val string) *string { - return &val -} - func testNotify() Notify { return Notify{ URLFields: map[string]string{ @@ -53,11 +38,3 @@ func testNotify() Notify { }, } } - -func trimJSON(str string) string { - str = strings.TrimSpace(str) - str = strings.ReplaceAll(str, "\n", "") - str = strings.ReplaceAll(str, "\t", "") - str = strings.ReplaceAll(str, ": ", ":") - return str -} diff --git a/web/api/types/websocket_test.go b/web/api/types/websocket_test.go index 2aae6045..4c0fd7da 100644 --- a/web/api/types/websocket_test.go +++ b/web/api/types/websocket_test.go @@ -20,6 +20,8 @@ import ( "strings" "testing" "time" + + "github.com/release-argus/Argus/test" ) func TestWebSocketMessage_String(t *testing.T) { @@ -38,22 +40,22 @@ func TestWebSocketMessage_String(t *testing.T) { }, "filled": { websocketMessage: WebSocketMessage{ - Version: intPtr(1), + Version: test.IntPtr(1), Page: "foo", Type: "bar", SubType: "baz", - Target: stringPtr("bish"), + Target: test.StringPtr("bish"), Order: &[]string{ "zing", "zap", "wallop"}, ServiceData: &ServiceSummary{ ID: "summary id"}, CommandData: map[string]*CommandSummary{ "alpha": { - Failed: boolPtr(true), + Failed: test.BoolPtr(true), NextRunnable: time.Date(2010, 1, 1, 0, 0, 0, 0, time.UTC)}}, WebHookData: map[string]*WebHookSummary{ "omega": { - Failed: boolPtr(true), + Failed: test.BoolPtr(true), NextRunnable: time.Date(2020, 2, 2, 0, 0, 0, 0, time.UTC)}}}, want: ` { @@ -86,7 +88,7 @@ func TestWebSocketMessage_String(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - tc.want = trimJSON(tc.want) + tc.want = test.TrimJSON(tc.want) // WHEN the GitHubData is stringified with String got := tc.websocketMessage.String() diff --git a/web/api/v1/help_test.go b/web/api/v1/help_test.go index 1de380c9..34bc0f28 100644 --- a/web/api/v1/help_test.go +++ b/web/api/v1/help_test.go @@ -18,7 +18,6 @@ package v1 import ( "os" - "strings" "sync" "testing" @@ -152,32 +151,6 @@ func testCommand(failing bool) command.Command { return command.Command{"ls", "-lah"} } -func testWebHook(failing bool, id string) *webhook.WebHook { - whDesiredStatusCode := 0 - whMaxTries := uint(1) - wh := webhook.New( - test.BoolPtr(false), - nil, - "0s", - &whDesiredStatusCode, - nil, - &whMaxTries, - nil, - test.StringPtr("11m"), - "argus", - test.BoolPtr(false), - "github", - "https://valid.release-argus.io/hooks/github-style", - &webhook.WebHookDefaults{}, - &webhook.WebHookDefaults{}, - &webhook.WebHookDefaults{}) - wh.ID = id - if failing { - wh.Secret = "notArgus" - } - return wh -} - func testFaviconSettings(png string, svg string) *config.FaviconSettings { if svg == "" && png == "" { return nil @@ -187,11 +160,3 @@ func testFaviconSettings(png string, svg string) *config.FaviconSettings { SVG: svg, PNG: png} } - -func trimJSON(str string) string { - str = strings.TrimSpace(str) - str = strings.ReplaceAll(str, "\n", "") - str = strings.ReplaceAll(str, "\t", "") - str = strings.ReplaceAll(str, ": ", ":") - return str -} diff --git a/web/api/v1/http-api-actions_test.go b/web/api/v1/http-api-actions_test.go index a5b8c4a7..1503cc10 100644 --- a/web/api/v1/http-api-actions_test.go +++ b/web/api/v1/http-api-actions_test.go @@ -36,6 +36,7 @@ import ( "github.com/release-argus/Argus/util" api_type "github.com/release-argus/Argus/web/api/types" "github.com/release-argus/Argus/webhook" + test_webhook "github.com/release-argus/Argus/webhook/test" ) func TestHTTP_httpServiceGetActions(t *testing.T) { @@ -86,21 +87,21 @@ func TestHTTP_httpServiceGetActions(t *testing.T) { "known service_id, 0 command, 1 webhooks": { serviceID: "__name__", webhooks: webhook.Slice{ - "fail0": testWebHook(true, "fail0")}, + "fail0": test_webhook.WebHook(true, false, false)}, }, "known service_id, 0 command, 2 webhooks": { serviceID: "__name__", webhooks: webhook.Slice{ - "fail0": testWebHook(true, "fail0"), - "pass0": testWebHook(false, "pass0")}, + "fail0": test_webhook.WebHook(true, false, false), + "pass0": test_webhook.WebHook(false, false, false)}, }, "known service_id, 2 command, 2 webhooks": { serviceID: "__name__", commands: command.Slice{ testCommand(true), testCommand(false)}, webhooks: webhook.Slice{ - "fail0": testWebHook(true, "fail0"), - "pass0": testWebHook(false, "pass0")}, + "fail0": test_webhook.WebHook(true, false, false), + "pass0": test_webhook.WebHook(false, false, false)}, }, } cfg := api.Config @@ -323,14 +324,14 @@ func TestHTTP_httpServiceRunActions(t *testing.T) { serviceID: "__name__", target: test.StringPtr("ARGUS_ALL"), webhooks: webhook.Slice{ - "known-service-and-webhook": testWebHook(true, "known-service-and-webhook")}, + "known-service-and-webhook": test_webhook.WebHook(true, false, false)}, }, "ARGUS_ALL, known service_id with multiple webhooks": { serviceID: "__name__", target: test.StringPtr("ARGUS_ALL"), webhooks: webhook.Slice{ - "known-service-and-multiple-webhook-0": testWebHook(true, "known-service-and-multiple-webhook-0"), - "known-service-and-multiple-webhook-1": testWebHook(true, "known-service-and-multiple-webhook-1")}, + "known-service-and-multiple-webhook-0": test_webhook.WebHook(true, false, false), + "known-service-and-multiple-webhook-1": test_webhook.WebHook(true, false, false)}, }, "ARGUS_ALL, known service_id with multiple commands": { serviceID: "__name__", @@ -344,7 +345,7 @@ func TestHTTP_httpServiceRunActions(t *testing.T) { commands: command.Slice{ {"ls", "-b"}}, webhooks: webhook.Slice{ - "known-service-dvl-webhook-0": testWebHook(false, "known-service-dvl-webhook-0")}, + "known-service-dvl-webhook-0": test_webhook.WebHook(false, false, false)}, upgradesApprovedVersion: true, latestVersion: "0.9.0", }, @@ -354,8 +355,7 @@ func TestHTTP_httpServiceRunActions(t *testing.T) { commands: command.Slice{ {"ls", "-c"}}, webhooks: webhook.Slice{ - "known-service-upgrade-deployed-version-webhook-0": testWebHook(false, - "known-service-upgrade-deployed-version-webhook-0")}, + "known-service-upgrade-deployed-version-webhook-0": test_webhook.WebHook(false, false, false)}, removeDVL: true, upgradesDeployedVersion: true, latestVersion: "0.9.0", @@ -366,7 +366,7 @@ func TestHTTP_httpServiceRunActions(t *testing.T) { commands: command.Slice{ {"ls", "-d"}}, webhooks: webhook.Slice{ - "known-service-fail-webhook-0": testWebHook(true, "known-service-fail-webhook-0")}, + "known-service-fail-webhook-0": test_webhook.WebHook(true, false, false)}, latestVersionIsApproved: true, }, "ARGUS_ALL, known service_id with failing command and passing webhook doesn't upgrade any versions": { @@ -375,7 +375,7 @@ func TestHTTP_httpServiceRunActions(t *testing.T) { commands: command.Slice{ {"fail"}}, webhooks: webhook.Slice{ - "known-service-pass-webhook-0": testWebHook(false, "known-service-pass-webhook-0")}, + "known-service-pass-webhook-0": test_webhook.WebHook(false, false, false)}, latestVersionIsApproved: true, }, "webhook_NAME, known service_id with 1 webhook left to pass does upgrade deployed_version": { @@ -386,8 +386,8 @@ func TestHTTP_httpServiceRunActions(t *testing.T) { commandFails: []*bool{ test.BoolPtr(false)}, webhooks: webhook.Slice{ - "will_pass": testWebHook(false, "will_pass"), - "would_fail": testWebHook(true, "would_fail")}, + "will_pass": test_webhook.WebHook(false, false, false), + "would_fail": test_webhook.WebHook(true, false, false)}, webhookFails: map[string]*bool{ "will_pass": test.BoolPtr(true), "would_fail": test.BoolPtr(false)}, @@ -405,7 +405,7 @@ func TestHTTP_httpServiceRunActions(t *testing.T) { test.BoolPtr(false), test.BoolPtr(true)}, webhooks: webhook.Slice{ - "would_fail": testWebHook(true, "would_fail")}, + "would_fail": test_webhook.WebHook(true, false, false)}, webhookFails: map[string]*bool{ "would_fail": test.BoolPtr(false)}, removeDVL: true, diff --git a/web/api/v1/http-api-config_test.go b/web/api/v1/http-api-config_test.go index 4a8b17a8..b8dd4eff 100644 --- a/web/api/v1/http-api-config_test.go +++ b/web/api/v1/http-api-config_test.go @@ -558,7 +558,7 @@ func TestHTTP_Config(t *testing.T) { if tc.order != nil { api.Config.Order = *tc.order } - tc.wantBody = trimJSON(tc.wantBody) + "\n" + tc.wantBody = test.TrimJSON(tc.wantBody) + "\n" // WHEN that HTTP request is sent req := httptest.NewRequest(http.MethodGet, "/api/v1/config", nil) diff --git a/web/api/v1/http-api-edit_test.go b/web/api/v1/http-api-edit_test.go index 88a15b8c..2d356ebb 100644 --- a/web/api/v1/http-api-edit_test.go +++ b/web/api/v1/http-api-edit_test.go @@ -436,7 +436,7 @@ func TestHTTP_OtherServiceDetails(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - tc.wantBody = trimJSON(tc.wantBody) + tc.wantBody = test.TrimJSON(tc.wantBody) svc := testService(name) defer func() { os.RemoveAll(file) diff --git a/web/help_test.go b/web/help_test.go index 2da19ce8..449abd66 100644 --- a/web/help_test.go +++ b/web/help_test.go @@ -33,12 +33,14 @@ import ( "github.com/release-argus/Argus/config" dbtype "github.com/release-argus/Argus/db/types" "github.com/release-argus/Argus/notifiers/shoutrrr" + test_shoutrrr "github.com/release-argus/Argus/notifiers/shoutrrr/test" "github.com/release-argus/Argus/service" deployedver "github.com/release-argus/Argus/service/deployed_version" latestver "github.com/release-argus/Argus/service/latest_version" "github.com/release-argus/Argus/service/latest_version/filter" opt "github.com/release-argus/Argus/service/options" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" "github.com/release-argus/Argus/webhook" ) @@ -46,23 +48,6 @@ import ( var mainCfg *config.Config var port *string -func boolPtr(val bool) *bool { - return &val -} -func intPtr(val int) *int { - return &val -} -func stringPtr(val string) *string { - return &val -} -func stringifyPointer[T comparable](ptr *T) string { - str := "nil" - if ptr != nil { - str = fmt.Sprint(*ptr) - } - return str -} - func TestMain(m *testing.M) { // initialize jLog jLog := util.NewJLog("DEBUG", false) @@ -74,7 +59,7 @@ func TestMain(m *testing.M) { os.Remove(file) defer os.Remove(*mainCfg.Settings.Data.DatabaseFile) port = mainCfg.Settings.Web.ListenPort - mainCfg.Settings.Web.ListenHost = stringPtr("localhost") + mainCfg.Settings.Web.ListenHost = test.StringPtr("localhost") // WHEN the Router is fetched for this Config router = newWebUI(mainCfg) @@ -85,12 +70,21 @@ func TestMain(m *testing.M) { os.Exit(code) } +func getFreePort() (int, error) { + ln, err := net.Listen("tcp", ":0") + if err != nil { + return 0, err + } + ln.Close() + return ln.Addr().(*net.TCPAddr).Port, nil +} + func testConfig(path string, jLog *util.JLog, t *testing.T) (cfg *config.Config) { testYAML_Argus(path, t) cfg = &config.Config{} // Settings.Log - cfg.Settings.Log.Level = stringPtr("DEBUG") + cfg.Settings.Log.Level = test.StringPtr("DEBUG") cfg.Load( path, @@ -128,17 +122,7 @@ func testConfig(path string, jLog *util.JLog, t *testing.T) (cfg *config.Config) emptyNotify := shoutrrr.ShoutrrrDefaults{} emptyNotify.InitMaps() notify := shoutrrr.Slice{ - "test": shoutrrr.New( - nil, - "test", - &map[string]string{ - "message": "{{ service_id }} release"}, - &map[string]string{}, - "", - &map[string]string{}, - &emptyNotify, - &emptyNotify, - &emptyNotify)} + "test": test_shoutrrr.Shoutrrr(false, false)} notify["test"].Params = map[string]string{} svc.Notify = notify svc.Comment = "test service's comment" @@ -163,15 +147,6 @@ func testConfig(path string, jLog *util.JLog, t *testing.T) (cfg *config.Config) return } -func getFreePort() (int, error) { - ln, err := net.Listen("tcp", ":0") - if err != nil { - return 0, err - } - ln.Close() - return ln.Addr().(*net.TCPAddr).Port, nil -} - func testService(id string) (svc *service.Service) { var ( sAnnounceChannel chan []byte = make(chan []byte, 2) @@ -183,8 +158,8 @@ func testService(id string) (svc *service.Service) { svc = &service.Service{ ID: id, LatestVersion: *latestver.New( - stringPtr(""), - boolPtr(false), + test.StringPtr(""), + test.BoolPtr(false), nil, nil, &filter.Require{ RegexContent: "content", @@ -198,17 +173,17 @@ func testService(id string) (svc *service.Service) { "url", "https://release-argus.io", &filter.URLCommandSlice{testURLCommandRegex()}, - boolPtr(false), + test.BoolPtr(false), nil, nil), DeployedVersionLookup: testDeployedVersion(), Options: *opt.New( nil, "10m", - boolPtr(true), + test.BoolPtr(true), &opt.OptionsDefaults{}, &opt.OptionsDefaults{}), Dashboard: *service.NewDashboardOptions( - boolPtr(false), "test", "", "https://release-argus.io", + test.BoolPtr(false), "test", "", "https://release-argus.io", &service.DashboardOptionsDefaults{}, &service.DashboardOptionsDefaults{}), Defaults: &service.Defaults{}, HardDefaults: &service.Defaults{}, @@ -254,50 +229,17 @@ func testService(id string) (svc *service.Service) { return } -func testCommand(failing bool) command.Command { - if failing { - return command.Command{"ls", "-lah", "/root"} - } - return command.Command{"ls", "-lah"} -} - -func testWebHook(failing bool, id string) *webhook.WebHook { - whDesiredStatusCode := 0 - whMaxTries := uint(1) - wh := webhook.New( - boolPtr(false), - nil, - "0s", - &whDesiredStatusCode, - nil, - &whMaxTries, - nil, - stringPtr("11m"), - "argus", - boolPtr(false), - "github", - "https://valid.release-argus.io/hooks/github-style", - &webhook.WebHookDefaults{}, - &webhook.WebHookDefaults{}, - &webhook.WebHookDefaults{}) - wh.ID = id - if failing { - wh.Secret = "notArgus" - } - return wh -} - func testWebHookDefaults(failing bool) *webhook.WebHookDefaults { whDesiredStatusCode := 0 whMaxTries := uint(1) wh := webhook.NewDefaults( - boolPtr(false), + test.BoolPtr(false), nil, "0s", &whDesiredStatusCode, &whMaxTries, "argus", - boolPtr(false), + test.BoolPtr(false), "github", "https://valid.release-argus.io/hooks/github-style") if failing { @@ -340,6 +282,7 @@ func testURLCommandRegex() filter.URLCommand { Index: index, } } + func generateCertFiles(certFile, keyFile string) error { // Generate the certificate and private key // Generate a private key diff --git a/web/web_test.go b/web/web_test.go index 9457d696..d9335f82 100644 --- a/web/web_test.go +++ b/web/web_test.go @@ -126,8 +126,8 @@ func TestAccessibleHTTPS(t *testing.T) { util.GoVersion)}, } cfg := testConfig("TestAccessibleHTTPS.yml", nil, t) - cfg.Settings.Web.CertFile = stringPtr("TestAccessibleHTTPS_cert.pem") - cfg.Settings.Web.KeyFile = stringPtr("TestAccessibleHTTPS_key.pem") + cfg.Settings.Web.CertFile = test.StringPtr("TestAccessibleHTTPS_cert.pem") + cfg.Settings.Web.KeyFile = test.StringPtr("TestAccessibleHTTPS_key.pem") generateCertFiles(*cfg.Settings.Web.CertFile, *cfg.Settings.Web.KeyFile) defer os.Remove(*cfg.Settings.Web.CertFile) defer os.Remove(*cfg.Settings.Web.KeyFile) diff --git a/webhook/announce_test.go b/webhook/announce_test.go index fe1a3529..3911461c 100644 --- a/webhook/announce_test.go +++ b/webhook/announce_test.go @@ -21,6 +21,7 @@ import ( "testing" "time" + "github.com/release-argus/Argus/test" api_type "github.com/release-argus/Argus/web/api/types" ) @@ -39,11 +40,11 @@ func TestWebHook_AnnounceSend(t *testing.T) { }, "failed (failed=true) does delay by 15s": { timeDifference: 15 * time.Second, - failed: boolPtr(true), + failed: test.BoolPtr(true), }, "success (failed=false) does delay by 2*Interval": { timeDifference: 24 * time.Minute, - failed: boolPtr(false), + failed: test.BoolPtr(false), }, } @@ -77,8 +78,8 @@ func TestWebHook_AnnounceSend(t *testing.T) { } // if they failed status matches - got := stringifyPointer(parsed.WebHookData[webhook.ID].Failed) - want := stringifyPointer(webhook.Failed.Get(webhook.ID)) + got := test.StringifyPtr(parsed.WebHookData[webhook.ID].Failed) + want := test.StringifyPtr(webhook.Failed.Get(webhook.ID)) if got != want { t.Errorf("want failed=%s\ngot failed=%s", want, got) diff --git a/webhook/gets_test.go b/webhook/gets_test.go index aad3c38b..b7240fed 100644 --- a/webhook/gets_test.go +++ b/webhook/gets_test.go @@ -22,6 +22,8 @@ import ( "os" "testing" "time" + + "github.com/release-argus/Argus/test" ) func TestWebHook_GetAllowInvalidCerts(t *testing.T) { @@ -35,25 +37,25 @@ func TestWebHook_GetAllowInvalidCerts(t *testing.T) { }{ "root overrides all": { want: true, - root: boolPtr(true), - main: boolPtr(false), - dfault: boolPtr(false), - hardDefault: boolPtr(false), + root: test.BoolPtr(true), + main: test.BoolPtr(false), + dfault: test.BoolPtr(false), + hardDefault: test.BoolPtr(false), }, "main overrides default+hardDefault": { want: true, - main: boolPtr(true), - dfault: boolPtr(false), - hardDefault: boolPtr(false), + main: test.BoolPtr(true), + dfault: test.BoolPtr(false), + hardDefault: test.BoolPtr(false), }, "default overrides hardDefault": { want: true, - dfault: boolPtr(true), - hardDefault: boolPtr(false), + dfault: test.BoolPtr(true), + hardDefault: test.BoolPtr(false), }, "hardDefault is last resort": { want: true, - hardDefault: boolPtr(true), + hardDefault: test.BoolPtr(true), }, } @@ -200,25 +202,25 @@ func TestWebHook_GetDesiredStatusCode(t *testing.T) { }{ "root overrides all": { want: 1, - root: intPtr(1), - main: intPtr(2), - dfault: intPtr(2), - hardDefault: intPtr(2), + root: test.IntPtr(1), + main: test.IntPtr(2), + dfault: test.IntPtr(2), + hardDefault: test.IntPtr(2), }, "main overrides default+hardDefault": { want: 1, - main: intPtr(1), - dfault: intPtr(2), - hardDefault: intPtr(2), + main: test.IntPtr(1), + dfault: test.IntPtr(2), + hardDefault: test.IntPtr(2), }, "default overrides hardDefault": { want: 1, - dfault: intPtr(1), - hardDefault: intPtr(2), + dfault: test.IntPtr(1), + hardDefault: test.IntPtr(2), }, "hardDefault is last resort": { want: 1, - hardDefault: intPtr(1), + hardDefault: test.IntPtr(1), }, } @@ -255,25 +257,25 @@ func TestWebHook_GetMaxTries(t *testing.T) { }{ "root overrides all": { want: uint(1), - root: uintPtr(1), - main: uintPtr(2), - dfault: uintPtr(2), - hardDefault: uintPtr(2), + root: test.UIntPtr(1), + main: test.UIntPtr(2), + dfault: test.UIntPtr(2), + hardDefault: test.UIntPtr(2), }, "main overrides default+hardDefault": { want: uint(1), - main: uintPtr(1), - dfault: uintPtr(2), - hardDefault: uintPtr(2), + main: test.UIntPtr(1), + dfault: test.UIntPtr(2), + hardDefault: test.UIntPtr(2), }, "default overrides hardDefault": { want: uint(1), - dfault: uintPtr(1), - hardDefault: uintPtr(2), + dfault: test.UIntPtr(1), + hardDefault: test.UIntPtr(2), }, "hardDefault is last resort": { want: uint(1), - hardDefault: uintPtr(1), + hardDefault: test.UIntPtr(1), }, } @@ -552,25 +554,25 @@ func TestWebHook_GetSilentFails(t *testing.T) { }{ "root overrides all": { want: true, - root: boolPtr(true), - main: boolPtr(false), - dfault: boolPtr(false), - hardDefault: boolPtr(false), + root: test.BoolPtr(true), + main: test.BoolPtr(false), + dfault: test.BoolPtr(false), + hardDefault: test.BoolPtr(false), }, "main overrides default+hardDefault": { want: true, - main: boolPtr(true), - dfault: boolPtr(false), - hardDefault: boolPtr(false), + main: test.BoolPtr(true), + dfault: test.BoolPtr(false), + hardDefault: test.BoolPtr(false), }, "default overrides hardDefault": { want: true, - dfault: boolPtr(true), - hardDefault: boolPtr(false), + dfault: test.BoolPtr(true), + hardDefault: test.BoolPtr(false), }, "hardDefault is last resort": { want: true, - hardDefault: boolPtr(true), + hardDefault: test.BoolPtr(true), }, } @@ -758,11 +760,11 @@ func TestWebHook_SetExecuting(t *testing.T) { }, "failed (failed=true) does delay by 15s": { timeDifference: 15 * time.Second, - failed: boolPtr(true), + failed: test.BoolPtr(true), }, "success (failed=false) does delay by 2*Interval": { timeDifference: 24 * time.Minute, - failed: boolPtr(false), + failed: test.BoolPtr(false), }, } diff --git a/webhook/help_test.go b/webhook/help_test.go index 1c2c14e9..8f6ecbc0 100644 --- a/webhook/help_test.go +++ b/webhook/help_test.go @@ -17,36 +17,16 @@ package webhook import ( - "fmt" "os" "strings" "testing" "github.com/release-argus/Argus/notifiers/shoutrrr" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" ) -func boolPtr(val bool) *bool { - return &val -} -func intPtr(val int) *int { - return &val -} -func stringPtr(val string) *string { - return &val -} -func uintPtr(val int) *uint { - converted := uint(val) - return &converted -} -func stringifyPointer[T comparable](ptr *T) string { - str := "nil" - if ptr != nil { - str = fmt.Sprint(*ptr) - } - return str -} func TestMain(m *testing.M) { // initialize jLog jLog = util.NewJLog("DEBUG", false) @@ -64,16 +44,16 @@ func testWebHook(failing bool, selfSignedCert bool, customHeaders bool) *WebHook desiredStatusCode := 0 whMaxTries := uint(1) webhook := New( - boolPtr(false), + test.BoolPtr(false), nil, "0s", &desiredStatusCode, nil, &whMaxTries, nil, - stringPtr("12m"), + test.StringPtr("12m"), "argus", - boolPtr(false), + test.BoolPtr(false), "github", "https://valid.release-argus.io/hooks/github-style", &WebHookDefaults{}, @@ -83,7 +63,7 @@ func testWebHook(failing bool, selfSignedCert bool, customHeaders bool) *WebHook webhook.ServiceStatus = &svcstatus.Status{} webhook.ServiceStatus.Init( 0, 0, 1, - stringPtr("testServiceID"), + test.StringPtr("testServiceID"), nil) webhook.Failed = &webhook.ServiceStatus.Fails.WebHook serviceName := "testServiceID" @@ -116,13 +96,13 @@ func testWebHookDefaults(failing bool, selfSignedCert bool, customHeaders bool) desiredStatusCode := 0 whMaxTries := uint(1) webhook := NewDefaults( - boolPtr(false), + test.BoolPtr(false), nil, "0s", &desiredStatusCode, &whMaxTries, "argus", - boolPtr(false), + test.BoolPtr(false), "github", "https://valid.release-argus.io/hooks/github-style") if failing { @@ -140,35 +120,3 @@ func testWebHookDefaults(failing bool, selfSignedCert bool, customHeaders bool) } return webhook } - -func testNotifier(failing bool, selfSignedCert bool) *shoutrrr.Shoutrrr { - url := "valid.release-argus.io" - if selfSignedCert { - url = strings.Replace(url, "valid", "invalid", 1) - } - notifier := shoutrrr.New( - nil, - "test", - &map[string]string{ - "max_tries": "1"}, - &map[string]string{}, - "gotify", - &map[string]string{ - "host": url, - "path": "/gotify", - // trunk-ignore(gitleaks/generic-api-key) - "token": "AGE-LlHU89Q56uQ"}, - &shoutrrr.ShoutrrrDefaults{}, - &shoutrrr.ShoutrrrDefaults{}, - &shoutrrr.ShoutrrrDefaults{}) - notifier.ServiceStatus = &svcstatus.Status{} - notifier.ServiceStatus.Init( - 0, 1, 0, - stringPtr("testServiceID"), - stringPtr("https://example.com")) - notifier.Failed = ¬ifier.ServiceStatus.Fails.Shoutrrr - if failing { - notifier.URLFields["token"] = "invalid" - } - return notifier -} diff --git a/webhook/init_test.go b/webhook/init_test.go index 766111e0..b912c8ba 100644 --- a/webhook/init_test.go +++ b/webhook/init_test.go @@ -22,6 +22,7 @@ import ( "github.com/prometheus/client_golang/prometheus/testutil" "github.com/release-argus/Argus/notifiers/shoutrrr" svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" metric "github.com/release-argus/Argus/web/metrics" ) @@ -58,7 +59,7 @@ func TestSlice_Metrics(t *testing.T) { if tc.slice != nil { for name, s := range *tc.slice { s.ID = name - s.ServiceStatus = &svcstatus.Status{ServiceID: stringPtr(name + "-service")} + s.ServiceStatus = &svcstatus.Status{ServiceID: test.StringPtr(name + "-service")} } } @@ -102,7 +103,7 @@ func TestWebHook_Metrics(t *testing.T) { webhook := testWebHook(true, false, false) webhook.ID = name + "TestInitMetrics" - webhook.ServiceStatus.ServiceID = stringPtr(name + "TestInitMetrics") + webhook.ServiceStatus.ServiceID = test.StringPtr(name + "TestInitMetrics") if tc.isNil { webhook = nil } @@ -141,11 +142,11 @@ func TestWebHook_Init(t *testing.T) { var main WebHookDefaults var defaults WebHookDefaults var hardDefaults WebHookDefaults - status := svcstatus.Status{ServiceID: stringPtr("TestInit")} + status := svcstatus.Status{ServiceID: test.StringPtr("TestInit")} status.Init( 0, 0, 1, - stringPtr("TestInit"), - stringPtr("https://example.com")) + test.StringPtr("TestInit"), + test.StringPtr("https://example.com")) // WHEN Init is called on it webhook.Init( diff --git a/webhook/send_test.go b/webhook/send_test.go index d6b01876..433081c9 100644 --- a/webhook/send_test.go +++ b/webhook/send_test.go @@ -24,6 +24,7 @@ import ( "github.com/prometheus/client_golang/prometheus/testutil" "github.com/release-argus/Argus/notifiers/shoutrrr" + test_shoutrrr "github.com/release-argus/Argus/notifiers/shoutrrr/test" "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" metric "github.com/release-argus/Argus/web/metrics" @@ -40,7 +41,7 @@ func TestWebHook_Try(t *testing.T) { desiredStatusCode int }{ "invalid url": { - url: stringPtr("invalid:// test"), + url: test.StringPtr("invalid:// test"), errRegex: "failed to get .?http.request"}, "fail due to invalid secret": { wouldFail: true, @@ -156,14 +157,14 @@ func TestWebHook_Send(t *testing.T) { wouldFail: true, stdoutRegex: `WebHook gave 500.*invalid gotify token`, notifiers: shoutrrr.Slice{ - "fail": testNotifier(true, false)}, + "fail": test_shoutrrr.Shoutrrr(true, false)}, }, "doesn't try notifiers on fail if silentFails": { wouldFail: true, silentFails: true, stdoutRegex: `WebHook gave 500.*failed \d times to send the WebHook [^-]+-n$`, notifiers: shoutrrr.Slice{ - "fail": testNotifier(true, false)}, + "fail": test_shoutrrr.Shoutrrr(true, false)}, }, "doesn't send if deleting": { deleting: true, @@ -342,11 +343,11 @@ func TestNotifiers_SendWithNotifier(t *testing.T) { "successful notifier": { errRegex: "^$", shoutrrrNotifiers: &shoutrrr.Slice{ - "pass": testNotifier(false, false)}}, + "pass": test_shoutrrr.Shoutrrr(false, false)}}, "failing notifier": { errRegex: "invalid gotify token", shoutrrrNotifiers: &shoutrrr.Slice{ - "fail": testNotifier(true, false)}}, + "fail": test_shoutrrr.Shoutrrr(true, false)}}, } for name, tc := range tests { diff --git a/webhook/test/main.go b/webhook/test/main.go new file mode 100644 index 00000000..62012ffb --- /dev/null +++ b/webhook/test/main.go @@ -0,0 +1,81 @@ +// Copyright [2024] [Argus] +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build unit || integration + +package test + +import ( + "strings" + + svcstatus "github.com/release-argus/Argus/service/status" + "github.com/release-argus/Argus/test" + "github.com/release-argus/Argus/webhook" +) + +func WebHook(failing bool, selfSignedCert bool, customHeaders bool) *webhook.WebHook { + desiredStatusCode := 0 + whMaxTries := uint(1) + wh := webhook.New( + test.BoolPtr(false), + nil, + "0s", + &desiredStatusCode, + nil, + &whMaxTries, + nil, + test.StringPtr("12m"), + "argus", + test.BoolPtr(false), + "github", + "https://valid.release-argus.io/hooks/github-style", + &webhook.WebHookDefaults{}, + &webhook.WebHookDefaults{}, + &webhook.WebHookDefaults{}) + wh.ID = "test" + wh.ServiceStatus = &svcstatus.Status{} + wh.ServiceStatus.Init( + 0, 0, 1, + test.StringPtr("testServiceID"), + nil) + wh.Failed = &wh.ServiceStatus.Fails.WebHook + serviceName := "testServiceID" + webURL := "https://example.com" + wh.ServiceStatus.Init( + 0, 1, 0, + &serviceName, + &webURL) + if selfSignedCert { + wh.URL = strings.Replace(wh.URL, "valid", "invalid", 1) + } + if failing { + wh.Secret = "invalid" + } + if customHeaders { + wh.URL = strings.Replace(wh.URL, "github-style", "single-header", 1) + if failing { + wh.CustomHeaders = &webhook.Headers{ + {Key: "X-Test", Value: "invalid"}} + } else { + wh.CustomHeaders = &webhook.Headers{ + {Key: "X-Test", Value: "secret"}} + } + } + + // Slice to InitMetrics + slice := webhook.Slice{"test": wh} + slice.InitMetrics() + + return wh +} diff --git a/webhook/test/main_test.go b/webhook/test/main_test.go new file mode 100644 index 00000000..692144b3 --- /dev/null +++ b/webhook/test/main_test.go @@ -0,0 +1,241 @@ +// Copyright [2024] [Argus] +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build unit || integration + +package test + +import ( + "testing" + + "github.com/release-argus/Argus/webhook" +) + +func TestWebHook(t *testing.T) { + // GIVEN the failing, self-signed certificate, and custom headers flags + tests := map[string]struct { + failing bool + selfSignedCert bool + customHeaders bool + expectedURL string + expectedSecret string + expectedHeaders *webhook.Headers + }{ + "passing, signed, no custom headers": { + failing: false, + selfSignedCert: false, + customHeaders: false, + expectedURL: "https://valid.release-argus.io/hooks/github-style", + expectedSecret: "argus", + expectedHeaders: nil, + }, + "passing, signed, with custom headers": { + failing: false, + selfSignedCert: false, + customHeaders: true, + expectedURL: "https://valid.release-argus.io/hooks/single-header", + expectedSecret: "argus", + expectedHeaders: &webhook.Headers{{Key: "X-Test", Value: "secret"}}, + }, + "passing, self-signed, no custom headers": { + failing: false, + selfSignedCert: true, + customHeaders: false, + expectedURL: "https://invalid.release-argus.io/hooks/github-style", + expectedSecret: "argus", + expectedHeaders: nil, + }, + "passing, self-signed, with custom headers": { + failing: false, + selfSignedCert: true, + customHeaders: true, + expectedURL: "https://invalid.release-argus.io/hooks/single-header", + expectedSecret: "argus", + expectedHeaders: &webhook.Headers{{Key: "X-Test", Value: "secret"}}, + }, + "failing, signed, no custom headers": { + failing: true, + selfSignedCert: false, + customHeaders: false, + expectedURL: "https://valid.release-argus.io/hooks/github-style", + expectedSecret: "invalid", + expectedHeaders: nil, + }, + "failing, signed, with custom headers": { + failing: true, + selfSignedCert: false, + customHeaders: true, + expectedURL: "https://valid.release-argus.io/hooks/single-header", + expectedSecret: "invalid", + expectedHeaders: &webhook.Headers{{Key: "X-Test", Value: "invalid"}}, + }, + "failing, self-signed, no custom headers": { + failing: true, + selfSignedCert: true, + customHeaders: false, + expectedURL: "https://invalid.release-argus.io/hooks/github-style", + expectedSecret: "invalid", + expectedHeaders: nil, + }, + "failing, self-signed, with custom headers": { + failing: true, + selfSignedCert: true, + customHeaders: true, + expectedURL: "https://invalid.release-argus.io/hooks/single-header", + expectedSecret: "invalid", + expectedHeaders: &webhook.Headers{{Key: "X-Test", Value: "invalid"}}, + }, + } + + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + + // WHEN WebHook is called + got := WebHook(tc.failing, tc.selfSignedCert, tc.customHeaders) + + // THEN the URL should be as expected + if got.URL != tc.expectedURL { + t.Errorf("URL: expected %q but got %q", + tc.expectedURL, got.URL) + } + + // AND the secret should be as expected + if got.Secret != tc.expectedSecret { + t.Errorf("Secret: expected %q but got %q", + tc.expectedSecret, got.Secret) + } + + // AND the custom headers should be as expected + if tc.expectedHeaders == nil { + if got.CustomHeaders != nil { + t.Errorf("CustomHeaders: expected nil but got %+v", + got.CustomHeaders) + } + } else { + if got.CustomHeaders == nil { + t.Errorf("CustomHeaders: expected %+v but got nil", + tc.expectedHeaders) + } else { + // Length differ + if len(*got.CustomHeaders) != len(*tc.expectedHeaders) { + t.Errorf("CustomHeaders: length differs, expected %+v but got %+v", + tc.expectedHeaders, got.CustomHeaders) + } else { + // Check each header + for i := range *tc.expectedHeaders { + if (*tc.expectedHeaders)[i].Key != (*got.CustomHeaders)[i].Key || + (*tc.expectedHeaders)[i].Value != (*got.CustomHeaders)[i].Value { + t.Errorf("CustomHeaders: expected %+v but got %+v", + tc.expectedHeaders, got.CustomHeaders) + break + } + } + } + } + } + + // AND the ID should be set + if got.ID != "test" { + t.Errorf("ID: expected %q but got %q", + "test", got.ID) + } + + // AND the ServiceStatus should be initialized + if got.ServiceStatus == nil { + t.Error("ServiceStatus not initialized") + } + + // AND the Fails should be set + if got.ServiceStatus == nil || got.Failed == nil { + if got.Failed == nil { + t.Error("Failed not set") + } else { + t.Error("ServiceStatus not set") + } + } + + // AND the desiredStatusCode should be set + if got.DesiredStatusCode == nil || *got.DesiredStatusCode != 0 { + if got.DesiredStatusCode == nil { + t.Error("DesiredStatusCode not set") + } else { + t.Errorf("DesiredStatusCode: expected %d but got %d", + 0, *got.DesiredStatusCode) + } + } + + // AND the MaxTries should be set + if got.MaxTries == nil || *got.MaxTries != 1 { + if got.MaxTries == nil { + t.Error("MaxTries not set") + } else { + t.Errorf("MaxTries: expected %d but got %d", + 1, *got.MaxTries) + } + } + + // AND the Delay should be set + wantDelay := "0s" + if got.Delay == "" || got.Delay != wantDelay { + if got.Delay == "" { + t.Error("Delay not set") + } else { + t.Errorf("Delay:expected %q but got %q", + wantDelay, got.Delay) + } + } + + // AND the Main should be set + if got.Main == nil { + t.Error("Main not set") + } + + // AND the Defaults should be set + if got.Defaults == nil { + t.Error("Defaults not set") + } + + // AND the HardDefaults should be set + if got.HardDefaults == nil { + t.Error("HardDefaults not set") + } + + // AND the URL should be modified if selfSignedCert is true + if tc.selfSignedCert { + if got.URL != tc.expectedURL { + t.Errorf("SelfSignedCert: url, expected %q but got %q", + tc.expectedURL, got.URL) + } + } + + // AND the Secret should be modified if failing is true + if tc.failing { + expectedSecret := "invalid" + if got.Secret != expectedSecret { + t.Errorf("Failing: url, expected %q but got %q", + expectedSecret, got.Secret) + } + } + + // AND the URL should be modified and custom headers should be set if customHeaders is true + if tc.customHeaders { + if got.URL != tc.expectedURL { + t.Errorf("CustomHeaders: url, expected %q but got %q", + tc.expectedURL, got.URL) + } + } + }) + } +} diff --git a/webhook/types_test.go b/webhook/types_test.go index f09643a6..63ffc54a 100644 --- a/webhook/types_test.go +++ b/webhook/types_test.go @@ -22,6 +22,7 @@ import ( "testing" "github.com/release-argus/Argus/notifiers/shoutrrr" + "github.com/release-argus/Argus/test" "github.com/release-argus/Argus/util" "gopkg.in/yaml.v3" ) @@ -134,15 +135,15 @@ func TestWebHookDefaults_String(t *testing.T) { }, "filled": { webhook: NewDefaults( - boolPtr(false), + test.BoolPtr(false), &Headers{ {Key: "X-Header", Value: "val"}, {Key: "X-Another", Value: "val2"}}, "1h1m1s", - intPtr(200), - uintPtr(4), + test.IntPtr(200), + test.UIntPtr(4), "foobar", - boolPtr(true), + test.BoolPtr(true), "github", "https://example.com"), want: ` @@ -215,33 +216,33 @@ func TestWebHook_String(t *testing.T) { }, "filled": { webhook: New( - boolPtr(false), // allow_invalid_certs + test.BoolPtr(false), // allow_invalid_certs &Headers{ // custom_headers {Key: "X-Header", Value: "val"}, {Key: "X-Another", Value: "val2"}}, - "1h1m1s", // delay - intPtr(200), // desired_status_code - nil, // failed - uintPtr(4), // max_tries + "1h1m1s", // delay + test.IntPtr(200), // desired_status_code + nil, // failed + test.UIntPtr(4), // max_tries &Notifiers{ // notifiers Shoutrrr: &shoutrrr.Slice{ "foo": shoutrrr.New( nil, "", nil, nil, "discord", nil, nil, nil, nil)}}, - stringPtr("3h2m1s"), // parent_interval - "foobar", // secret - boolPtr(true), // silent_fails - "github", // type - "https://example.com", // url + test.StringPtr("3h2m1s"), // parent_interval + "foobar", // secret + test.BoolPtr(true), // silent_fails + "github", // type + "https://example.com", // url NewDefaults( // main - boolPtr(false), + test.BoolPtr(false), nil, "", nil, nil, "", nil, "", ""), NewDefaults( // defaults - boolPtr(true), + test.BoolPtr(true), nil, "", nil, nil, "", nil, "", ""), NewDefaults( // hard_defaults - boolPtr(true), + test.BoolPtr(true), nil, "", nil, nil, "", nil, "", "")), want: ` type: github diff --git a/webhook/verify_test.go b/webhook/verify_test.go index e9309315..5895a03b 100644 --- a/webhook/verify_test.go +++ b/webhook/verify_test.go @@ -237,38 +237,38 @@ func TestWebHook_CheckValues(t *testing.T) { "invalid type": { errRegex: []string{ "^type: .*foo.* "}, - whType: stringPtr("foo"), + whType: test.StringPtr("foo"), }, "invalid main type": { errRegex: []string{}, // Invalid, but caught in the Defaults CheckValues - whType: stringPtr(""), + whType: test.StringPtr(""), whMainType: "bar", }, "mismatching type and main type": { errRegex: []string{ `^type: "github" != "gitlab" `}, - whType: stringPtr("github"), + whType: test.StringPtr("github"), whMainType: "gitlab", }, "no type": { errRegex: []string{ "^type: "}, - whType: stringPtr(""), + whType: test.StringPtr(""), }, "invalid url template": { errRegex: []string{ "url: .* "}, - url: stringPtr("{{ version }"), + url: test.StringPtr("{{ version }"), }, "no url": { errRegex: []string{ "^url: "}, - url: stringPtr(""), + url: test.StringPtr(""), }, "no secret": { errRegex: []string{ "^secret: "}, - secret: stringPtr(""), + secret: test.StringPtr(""), }, "valid custom headers": { customHeaders: Headers{ @@ -289,9 +289,9 @@ func TestWebHook_CheckValues(t *testing.T) { `^url: `, `^secret: `}, delay: "5x", - whType: stringPtr("foo"), - url: stringPtr(""), - secret: stringPtr(""), + whType: test.StringPtr("foo"), + url: test.StringPtr(""), + secret: test.StringPtr(""), }, }