|
| 1 | +package servicemessages |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/OctopusDeploy/cli/pkg/constants" |
| 8 | + "github.com/spf13/viper" |
| 9 | +) |
| 10 | + |
| 11 | +func TestServiceMessage(t *testing.T) { |
| 12 | + tests := []struct { |
| 13 | + name string |
| 14 | + servicemessages bool |
| 15 | + teamCityEnv bool |
| 16 | + messsageName string |
| 17 | + key string |
| 18 | + value any |
| 19 | + stdout *bytes.Buffer |
| 20 | + stderr *bytes.Buffer |
| 21 | + want string |
| 22 | + wantErr string |
| 23 | + }{ |
| 24 | + {"service message flag is not enabled", false, false, "testMessage", "key1", "value1", &bytes.Buffer{}, &bytes.Buffer{}, "", ""}, |
| 25 | + {"service message enabled with teamcity envvar and map value", true, true, "testMessage", "key1", map[string]string{"key": "value"}, &bytes.Buffer{}, &bytes.Buffer{}, "##teamcity[testMessage key=value]", ""}, |
| 26 | + {"service message enabled without teamcity envvar", true, false, "testMessage", "key1", "value1", &bytes.Buffer{}, &bytes.Buffer{}, "", "service messages are only supported in TeamCity builds"}, |
| 27 | + {"service message enabled with teamcity envvar and string value", true, true, "testMessage", "key1", "value", &bytes.Buffer{}, &bytes.Buffer{}, "##teamcity[testMessage value]\n", ""}, |
| 28 | + {"service message enabled with teamcity envvar and unsupported value", true, true, "testMessage", "key1", []string{"dsdsd"}, &bytes.Buffer{}, &bytes.Buffer{}, "", "Unsupported service message value type"}, |
| 29 | + } |
| 30 | + |
| 31 | + for _, tt := range tests { |
| 32 | + setupArgs(t, constants.FlagEnableServiceMessages, tt.servicemessages) |
| 33 | + setupEnvVar(t, "TEAMCITY_VERSION", "2021.1", tt.teamCityEnv) |
| 34 | + t.Run(tt.name, func(t *testing.T) { |
| 35 | + NewProvider(NewOutputPrinter(tt.stdout, tt.stderr)).ServiceMessage(tt.messsageName, tt.value) |
| 36 | + if tt.want != "" { |
| 37 | + got := tt.stdout.String() |
| 38 | + if got != tt.want { |
| 39 | + t.Errorf("Expected output:\n%s\nGot:\n%s", tt.want, got) |
| 40 | + } |
| 41 | + } |
| 42 | + if tt.wantErr != "" { |
| 43 | + e := tt.stderr.String() |
| 44 | + if e != tt.wantErr { |
| 45 | + t.Errorf("Expected error output:\n%s\nGot:\n%s", tt.wantErr, e) |
| 46 | + } |
| 47 | + } |
| 48 | + }) |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +func setupArgs(t *testing.T, key string, value bool) { |
| 53 | + viper.Reset() |
| 54 | + viper.Set(constants.FlagEnableServiceMessages, value) |
| 55 | +} |
| 56 | + |
| 57 | +func setupEnvVar(t *testing.T, key, value string, set bool) { |
| 58 | + if set { |
| 59 | + t.Setenv(key, value) |
| 60 | + } else { |
| 61 | + t.Setenv(key, "") |
| 62 | + } |
| 63 | +} |
0 commit comments