Skip to content

Commit

Permalink
Add print test coverage
Browse files Browse the repository at this point in the history
Signed-off-by: Terry Howe <[email protected]>
  • Loading branch information
TerryHowe committed May 7, 2024
1 parent d28bfcf commit b3a4199
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 5 deletions.
8 changes: 3 additions & 5 deletions cmd/oras/internal/display/status/print.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,9 @@ func (p *Printer) Println(a ...any) {
p.lock.Lock()
defer p.lock.Unlock()
_, err := fmt.Fprintln(p.out, a...)
if err != nil {
if p.errored == nil {
p.errored = fmt.Errorf("display output error: %w", err)
_, _ = fmt.Fprint(os.Stderr, p.errored)
}
if err != nil && p.errored == nil {
p.errored = fmt.Errorf("display output error: %w", err)
_, _ = fmt.Fprint(os.Stderr, p.errored)
}
}

Expand Down
63 changes: 63 additions & 0 deletions cmd/oras/internal/display/status/print_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
Copyright The ORAS Authors.
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.
*/

package status

import (
"fmt"
"io"
"strings"
"testing"
)

type mockWriter struct{}

func (mw *mockWriter) Write(p []byte) (n int, err error) {
return 0, fmt.Errorf("Boom: " + string(p))
}

func TestPrint_Error(t *testing.T) {
foo := &mockWriter{}
printer := NewPrinter(foo)
printer.Println("one")
if printer.errored == nil {
t.Error("Print should error")
}
if printer.errored.Error() == "Boom: one" {
t.Error("Unexpected error text: " + printer.errored.Error())
}

printer.Println("two")
if printer.errored == nil {
t.Error("Print should still error")
}
if printer.errored.Error() == "Boom: one" {
t.Error("Unexpected error text second time: " + printer.errored.Error())
}
}

func TestPrint_NoError(t *testing.T) {
var ser strings.Builder
printer := NewPrinter(io.Writer(&ser))
expected := "blah blah"
printer.Println(expected)
if printer.errored != nil {
t.Error("Print should not error")
}
actual := strings.TrimSpace(ser.String())
if expected != actual {
t.Error("Expected <" + expected + "> not equal to actual <" + actual + ">")
}
}

0 comments on commit b3a4199

Please sign in to comment.