github.com/safedep/dry@v0.0.0-20241016050132-a15651f0548b/db/url_test.go (about) 1 package db 2 3 import ( 4 "testing" 5 6 "github.com/stretchr/testify/assert" 7 ) 8 9 func TestDatabaseURL(t *testing.T) { 10 t.Run("when set", func(t *testing.T) { 11 t.Setenv(databaseDSNEnvKey, "postgresql://user:@localhost:5432/dbname") 12 13 got, err := DatabaseURL() 14 assert.NoError(t, err) 15 assert.Equal(t, "postgresql://user:@localhost:5432/dbname", got) 16 }) 17 18 t.Run("when not set", func(t *testing.T) { 19 got, err := DatabaseURL() 20 assert.ErrorContains(t, err, errDatabaseDSNNotSet.Error()) 21 assert.Empty(t, got) 22 }) 23 } 24 25 func TestMigrationDatabaseURL(t *testing.T) { 26 cases := []struct { 27 name string 28 dbEnvVal string 29 migrationEnvVal string 30 want string 31 wantErr error 32 }{ 33 { 34 name: "database DSN environment is set", 35 dbEnvVal: "postgresql://user:@localhost:5432/dbname", 36 migrationEnvVal: "", 37 want: "postgresql://user:@localhost:5432/dbname", 38 wantErr: nil, 39 }, 40 { 41 name: "migration DSN environment is set", 42 dbEnvVal: "", 43 migrationEnvVal: "postgresql://user:@localhost:5432/dbname", 44 want: "postgresql://user:@localhost:5432/dbname", 45 wantErr: nil, 46 }, 47 { 48 name: "both DSN environments are set", 49 dbEnvVal: "postgresql://user:@localhost:5432/dbname1", 50 migrationEnvVal: "postgresql://user:@localhost:5432/dbname2", 51 want: "postgresql://user:@localhost:5432/dbname2", 52 wantErr: nil, 53 }, 54 { 55 name: "none are set", 56 dbEnvVal: "", 57 migrationEnvVal: "", 58 want: "", 59 wantErr: errDatabaseDSNEmpty, 60 }, 61 { 62 name: "invalid database DSN", 63 dbEnvVal: "invalid", 64 migrationEnvVal: "", 65 want: "", 66 wantErr: errDatabaseSchemeInvalid, 67 }, 68 } 69 70 for _, test := range cases { 71 t.Run(test.name, func(t *testing.T) { 72 t.Setenv(databaseDSNEnvKey, test.dbEnvVal) 73 t.Setenv(databaseMigrationDSNEnvKey, test.migrationEnvVal) 74 75 got, err := DatabaseMigrationURL() 76 if test.wantErr != nil { 77 assert.ErrorContains(t, err, test.wantErr.Error()) 78 } else { 79 assert.NoError(t, err) 80 assert.Equal(t, test.want, got) 81 } 82 }) 83 } 84 }