Files
mtusi2026lab5/internal/processing/worker_test.go
T

65 lines
1.9 KiB
Go

package processing
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"io"
"log/slog"
"strings"
"testing"
"messenger/internal/attachment"
"messenger/internal/pipeline"
)
type stagedSource struct {
attachment.Blobs
body string
}
func (s stagedSource) Open(context.Context, string) (io.ReadCloser, error) {
return io.NopCloser(strings.NewReader(s.body)), nil
}
func TestReadOriginalValidatesPersistedSizeAndDigest(t *testing.T) {
h := sha256.Sum256([]byte("accepted"))
c := &pipeline.Claim{SizeBytes: 8, Hash: h[:], SourceKey: "staging/test"}
for _, bad := range []string{"accept", "altered!", "oversized bytes"} {
_, err := readOriginal(t.Context(), stagedSource{body: bad}, c)
if !errors.Is(err, errSourceMismatch) {
t.Fatalf("body %q: %v", bad, err)
}
}
got, err := readOriginal(t.Context(), stagedSource{body: "accepted"}, c)
if err != nil || string(got) != "accepted" {
t.Fatalf("valid original: %v", err)
}
}
type failingSource struct{ attachment.Blobs }
func (failingSource) Open(context.Context, string) (io.ReadCloser, error) {
return nil, fmt.Errorf("credentials=private-source-data: %w", context.DeadlineExceeded)
}
func TestFailureLogReportsStageAndReason(t *testing.T) {
var log strings.Builder
w := Worker{Blobs: failingSource{}, Log: slog.New(slog.NewJSONHandler(&log, nil))}
c := &pipeline.Claim{SizeBytes: 5, SourceKey: "sensitive-source-key"}
_, failure := w.writeObjects(t.Context(), c)
if failure == nil {
t.Fatal("expected failure reading source")
}
got := log.String()
for _, want := range []string{`"stage":"read_original"`, `"reason":"deadline_exceeded"`, `"error_code":"processing_failed"`, `"job_id":`, `"attempt":`} {
if !strings.Contains(got, want) {
t.Errorf("log missing %s: %s", want, got)
}
}
if strings.Contains(got, "private-source-data") || strings.Contains(got, "sensitive-source-key") {
t.Errorf("leaked source details: %s", got)
}
}