package output_test
import (
"bytes"
"io"
"strings"
"testing"
"time"
"mercemay.top/src/lambdalog/output"
)
func TestCloudWatch_FlushesEveryWriteByDefault(t *testing.T) {
var buf bytes.Buffer
w := output.CloudWatch(&buf, output.CloudWatchOptions{})
if _, err := io.WriteString(w, "a\n"); err != nil {
t.Fatalf("write: %v", err)
}
if buf.String() != "a\n" {
t.Fatalf("got %q", buf.String())
}
}
func TestCloudWatch_BatchesWhenEveryN(t *testing.T) {
var buf bytes.Buffer
w := output.CloudWatch(&buf, output.CloudWatchOptions{FlushEvery: 3})
for i := 0; i < 2; i++ {
io.WriteString(w, "x\n")
}
if buf.Len() != 0 {
t.Fatalf("flushed too early: %q", buf.String())
}
io.WriteString(w, "x\n")
if count := strings.Count(buf.String(), "x\n"); count != 3 {
t.Fatalf("count=%d, want 3", count)
}
}
func TestCloudWatch_TruncatesOversizeLines(t *testing.T) {
var buf bytes.Buffer
w := output.CloudWatch(&buf, output.CloudWatchOptions{MaxLineBytes: 4})
io.WriteString(w, "abcdefgh")
if buf.String() != "abcd" {
t.Fatalf("got %q", buf.String())
}
}
func TestCloudWatch_FlushViaInterface(t *testing.T) {
var buf bytes.Buffer
w := output.CloudWatch(&buf, output.CloudWatchOptions{FlushEvery: 10})
io.WriteString(w, "x\n")
f, ok := w.(output.Flusher)
if !ok {
t.Fatal("not a Flusher")
}
if err := f.Flush(); err != nil {
t.Fatalf("flush: %v", err)
}
if buf.String() != "x\n" {
t.Fatalf("got %q", buf.String())
}
}
func TestCloudWatch_CloseFlushes(t *testing.T) {
var buf bytes.Buffer
w := output.CloudWatch(&buf, output.CloudWatchOptions{FlushEvery: 10, FlushInterval: time.Hour})
io.WriteString(w, "x\n")
closer, ok := w.(io.Closer)
if !ok {
t.Fatal("not a Closer")
}
if err := closer.Close(); err != nil {
t.Fatalf("close: %v", err)
}
if buf.String() != "x\n" {
t.Fatalf("got %q", buf.String())
}
if _, err := io.WriteString(w, "after"); err == nil {
t.Fatal("write after close should fail")
}
}