Files
archie/internal/webui/api_audit_test.go
T

91 lines
2.8 KiB
Go

package webui
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/samcharles93/archie-core/internal/domain/audit"
)
type auditStub struct {
page audit.Page
err error
}
func (s auditStub) ListAudit(context.Context, audit.Filter, audit.Cursor, int) (audit.Page, error) {
return s.page, s.err
}
func (s auditStub) AuditHead(context.Context) (string, error) { return "", nil }
// TestAuditCSVCellNeutralisesFormulas pins the export's spreadsheet boundary:
// a value a spreadsheet would evaluate is text, while ordinary values are
// unchanged.
func TestAuditCSVCellNeutralisesFormulas(t *testing.T) {
tests := []struct {
name string
in string
want string
}{
{"equals", "=1+1", "'=1+1"},
{"plus", "+cmd", "'+cmd"},
{"minus", "-2", "'-2"},
{"at", "@SUM(A1)", "'@SUM(A1)"},
{"tab", "\tcmd", "'\tcmd"},
{"carriage return", "\r=cmd", "'\r=cmd"},
{"ordinary", "alice", "alice"},
{"empty", "", ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := csvCell(tt.in); got != tt.want {
t.Fatalf("csvCell(%q) = %q, want %q", tt.in, got, tt.want)
}
})
}
}
// TestAuditErrorMapping pins how a failed feed read reaches the browser: bad
// input is the caller's fault, a denial is forbidden, and an unreadable feed
// is unavailable rather than an empty page.
func TestAuditErrorMapping(t *testing.T) {
tests := []struct {
name string
err error
want int
body string
}{
{"invalid filter", status.Error(codes.InvalidArgument, "invalid audit filter: unknown category \"nope\"\nsecond line"), http.StatusBadRequest, "invalid audit filter: unknown category \"nope\""},
{"denied", status.Error(codes.PermissionDenied, "forbidden"), http.StatusForbidden, "forbidden"},
{"unavailable", status.Error(codes.Unavailable, "state store unavailable"), http.StatusServiceUnavailable, "state store unavailable"},
{"internal", status.Error(codes.Internal, "boom"), http.StatusInternalServerError, "boom"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv := &Server{Audit: auditStub{err: tt.err}}
rec := httptest.NewRecorder()
srv.handleAudit(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/audit", nil))
if rec.Code != tt.want {
t.Fatalf("status = %d, want %d", rec.Code, tt.want)
}
if got := strings.TrimSpace(rec.Body.String()); got != tt.body {
t.Fatalf("body = %q, want %q", got, tt.body)
}
})
}
}
func TestAuditUnavailableWithoutFeed(t *testing.T) {
rec := httptest.NewRecorder()
(&Server{}).handleAudit(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/audit", nil))
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusServiceUnavailable)
}
}