fix postgres constraints, add postgres testing

This commit fixes the constraint syntax so it is both valid for
sqlite and postgres.

To validate this, I've added a new postgres testing library and a
helper that will spin up local postgres, setup a db and use it in
the constraints tests. This should also help testing db stuff in
the future.

postgres has been added to the nix dev shell and is now required
for running the unit tests.

Signed-off-by: Kristoffer Dalby <kristoffer@tailscale.com>
This commit is contained in:
Kristoffer Dalby 2024-11-23 11:19:52 +01:00 committed by Juan Font
parent 7d9b430ec2
commit f6276ab9d2
7 changed files with 95 additions and 21 deletions

View file

@ -9,6 +9,7 @@ import (
"path/filepath"
"slices"
"sort"
"strings"
"testing"
"time"
@ -259,6 +260,16 @@ func emptyCache() *zcache.Cache[string, types.Node] {
return zcache.New[string, types.Node](time.Minute, time.Hour)
}
// requireConstraintFailed checks if the error is a constraint failure with
// either SQLite and PostgreSQL error messages.
func requireConstraintFailed(t *testing.T, err error) {
t.Helper()
require.Error(t, err)
if !strings.Contains(err.Error(), "UNIQUE constraint failed:") && !strings.Contains(err.Error(), "violates unique constraint") {
require.Failf(t, "expected error to contain a constraint failure, got: %s", err.Error())
}
}
func TestConstraints(t *testing.T) {
tests := []struct {
name string
@ -270,9 +281,7 @@ func TestConstraints(t *testing.T) {
_, err := CreateUser(db, "user1")
require.NoError(t, err)
_, err = CreateUser(db, "user1")
require.Error(t, err)
assert.Contains(t, err.Error(), "UNIQUE constraint failed:")
// require.Contains(t, err.Error(), "user already exists")
requireConstraintFailed(t, err)
},
},
{
@ -294,8 +303,7 @@ func TestConstraints(t *testing.T) {
user.ProviderIdentifier = sql.NullString{String: "http://test.com/user1", Valid: true}
err = db.Save(&user).Error
require.Error(t, err)
require.Contains(t, err.Error(), "UNIQUE constraint failed:")
requireConstraintFailed(t, err)
},
},
{
@ -317,8 +325,7 @@ func TestConstraints(t *testing.T) {
user.ProviderIdentifier = sql.NullString{String: "http://test.com/user1", Valid: true}
err = db.Save(&user).Error
require.Error(t, err)
require.Contains(t, err.Error(), "UNIQUE constraint failed:")
requireConstraintFailed(t, err)
},
},
{
@ -354,8 +361,12 @@ func TestConstraints(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
db, err := newTestDB()
t.Run(tt.name+"-postgres", func(t *testing.T) {
db := newPostgresTestDB(t)
tt.run(t, db.DB.Debug())
})
t.Run(tt.name+"-sqlite", func(t *testing.T) {
db, err := newSQLiteTestDB()
if err != nil {
t.Fatalf("creating database: %s", err)
}