package database_test import ( "testing" "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "sneak.berlin/go/webhooker/internal/database" ) // newHTTPTarget returns an http target that makes maxAttempts attempts // at each delivery. func newHTTPTarget(maxAttempts int) *database.Target { return &database.Target{ WebhookID: uuid.New().String(), Name: "target", Type: database.TargetTypeHTTP, URL: "https://example.com/", MaxAttempts: maxAttempts, } } // TestTargetCreate_RefusesZeroAttempts relies on the targets table // alone: nothing in the model checks the number, so the check // constraint is what keeps a target with 0 attempts out of the // database. func TestTargetCreate_RefusesZeroAttempts(t *testing.T) { t.Parallel() db := startedTestDB(t) err := db.Create(newHTTPTarget(0)).Error require.Error(t, err) assert.Contains(t, err.Error(), "CHECK constraint failed") } func TestTargetCreate_AcceptsOneAttempt(t *testing.T) { t.Parallel() db := startedTestDB(t) require.NoError(t, db.Create(newHTTPTarget(1)).Error) } // TestTargetHeaders_StoredAsJSON reads the headers column back as // text, to show it holds the header map as JSON. func TestTargetHeaders_StoredAsJSON(t *testing.T) { t.Parallel() db := startedTestDB(t) target := newHTTPTarget(1) target.Headers = map[string]string{"Authorization": "Bearer x"} require.NoError(t, db.Create(target).Error) var headers string require.NoError(t, db.Raw( "SELECT headers FROM targets WHERE id = ?", target.ID, ).Scan(&headers).Error) assert.JSONEq(t, `{"Authorization":"Bearer x"}`, headers) }