Files
commandkit/integrations/ckconfig/report_cancellation_test.go

70 lines
2.4 KiB
Go
Raw Permalink Normal View History

package ckconfig
import (
"context"
"errors"
"io"
"testing"
commandkit "gitea.maximumdirect.net/eric/CommandKit"
)
func TestBufferedReportCancellationBeforeDelivery(t *testing.T) {
for _, quiet := range []bool{false, true} {
t.Run(map[bool]string{false: "ordinary", true: "quiet"}[quiet], func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
prepared := false
app := newConfigTestApp(t, commandkit.NewCommand(commandkit.CommandSpec[struct{}]{
Name: "report",
Run: func(invocation commandkit.Invocation, _ struct{}) commandkit.Outcome {
return renderPreparedConfigReport(invocation, commandkit.Explanation{Message: "selected context"}, func() ([]byte, error) {
prepared = true
cancel()
return []byte("prepared report"), nil
})
},
}))
args := []string{"report"}
if quiet {
args = append(args, "--quiet")
}
writes := 0
got := app.Execute(ctx, args, commandkit.Streams{Out: reportWriteFunc(func(p []byte) (int, error) {
writes++
return len(p), nil
})})
if !prepared || writes != 0 || got.Status != 1 || !errors.Is(got.Cause, context.Canceled) || got.Explanation.Message != "selected context" {
t.Fatalf("prepared=%t writes=%d outcome=%#v", prepared, writes, got)
}
if got.Presentation.Output.RenderError != nil || got.Presentation.Output.WriteError != nil {
t.Fatalf("cancellation became a presentation failure: %#v", got.Presentation.Output)
}
})
}
}
type reportWriteFunc func([]byte) (int, error)
func (write reportWriteFunc) Write(p []byte) (int, error) { return write(p) }
func TestBufferedReportDoesNotRejectCancellationAfterDeliveryStarts(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
app := newConfigTestApp(t, commandkit.NewCommand(commandkit.CommandSpec[struct{}]{
Name: "report",
Run: func(invocation commandkit.Invocation, _ struct{}) commandkit.Outcome {
return renderPreparedConfigReport(invocation, commandkit.Explanation{}, func() ([]byte, error) {
return []byte("report"), nil
})
},
}))
got := app.Execute(ctx, []string{"report"}, commandkit.Streams{Out: reportWriteFunc(func(p []byte) (int, error) {
cancel()
return io.Discard.Write(p)
})})
if got.Status != 0 || got.Cause != nil {
t.Fatalf("post-delivery cancellation changed the operation outcome: %#v", got)
}
}