From d29dbab75e977be43f9008db3a120d530303e8f3 Mon Sep 17 00:00:00 2001 From: Xiaoxuan Wang Date: Thu, 14 Mar 2024 09:46:06 +0000 Subject: [PATCH] added unit tests Signed-off-by: Xiaoxuan Wang --- cmd/oras/internal/option/common.go | 2 +- cmd/oras/internal/option/common_test.go | 44 +++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/cmd/oras/internal/option/common.go b/cmd/oras/internal/option/common.go index 55f45f145..9cd7b622c 100644 --- a/cmd/oras/internal/option/common.go +++ b/cmd/oras/internal/option/common.go @@ -70,7 +70,7 @@ func (opts *Common) parseTTY(f *os.File) error { // path value. func (opts *Common) UpdateTTY(flagPresent bool, toSTDOUT bool) { ttyEnforced := flagPresent && !opts.noTTY - if toSTDOUT && !ttyEnforced { + if opts.noTTY || (toSTDOUT && !ttyEnforced) { opts.TTY = nil } } diff --git a/cmd/oras/internal/option/common_test.go b/cmd/oras/internal/option/common_test.go index 6a035a820..a1534b622 100644 --- a/cmd/oras/internal/option/common_test.go +++ b/cmd/oras/internal/option/common_test.go @@ -16,6 +16,8 @@ limitations under the License. package option import ( + "os" + "reflect" "testing" "github.com/spf13/pflag" @@ -28,3 +30,45 @@ func TestCommon_FlagsInit(t *testing.T) { ApplyFlags(&test, pflag.NewFlagSet("oras-test", pflag.ExitOnError)) } + +func TestCommon_UpdateTTY(t *testing.T) { + testTTY := &os.File{} + tests := []struct { + name string + flagPresent bool + toSTDOUT bool + noTTY bool + expectedTTY *os.File + }{ + { + "output path == -, --no-tty flag not used", false, true, false, nil, + }, + { + "output path == -, --no-tty", true, true, true, nil, + }, + { + "output path == -, --no-tty=false", true, true, false, testTTY, + }, + { + "output path != -, --no-tty flag not used", false, false, false, testTTY, + }, + { + "output path != -, --no-tty", true, false, true, nil, + }, + { + "output path != -, --no-tty=false", true, false, false, testTTY, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + opts := &Common{ + noTTY: tt.noTTY, + TTY: testTTY, + } + opts.UpdateTTY(tt.flagPresent, tt.toSTDOUT) + if !reflect.DeepEqual(opts.TTY, tt.expectedTTY) { + t.Fatalf("tt.TTY got %v, want %v", opts.TTY, tt.expectedTTY) + } + }) + } +}