github.com/Redstoneguy129/cli@v0.0.0-20230211220159-15dca4e91917/internal/utils/connect_test.go (about)

     1  package utils
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  
     7  	"github.com/Redstoneguy129/cli/internal/testing/pgtest"
     8  	"github.com/spf13/viper"
     9  	"github.com/stretchr/testify/assert"
    10  	"github.com/stretchr/testify/require"
    11  )
    12  
    13  func TestConnectRemotePostgres(t *testing.T) {
    14  	t.Run("connects to remote postgres successfully", func(t *testing.T) {
    15  		// Setup mock postgres
    16  		conn := pgtest.NewConn()
    17  		defer conn.Close(t)
    18  		// Run test
    19  		c, err := ConnectRemotePostgres(context.Background(), "username", "password", "database", Config.Hostname, conn.Intercept)
    20  		require.NoError(t, err)
    21  		defer c.Close(context.Background())
    22  		assert.NoError(t, err)
    23  	})
    24  
    25  	t.Run("preserves db password", func(t *testing.T) {
    26  		// Setup mock postgres
    27  		conn := pgtest.NewConn()
    28  		defer conn.Close(t)
    29  		// Run test
    30  		password := "pass word"
    31  		c, err := ConnectRemotePostgres(context.Background(), "username", password, "database", Config.Hostname, conn.Intercept)
    32  		require.NoError(t, err)
    33  		defer c.Close(context.Background())
    34  		assert.Equal(t, password, c.Config().Password)
    35  	})
    36  }
    37  
    38  func TestConnectLocal(t *testing.T) {
    39  	t.Run("connects with debug log", func(t *testing.T) {
    40  		viper.Set("DEBUG", true)
    41  		_, err := ConnectLocalPostgres(context.Background(), "0", 5432, "postgres")
    42  		assert.ErrorContains(t, err, "dial error (dial tcp 0.0.0.0:5432: connect: connection refused)")
    43  	})
    44  
    45  	t.Run("throws error on invalid port", func(t *testing.T) {
    46  		_, err := ConnectLocalPostgres(context.Background(), Config.Hostname, 0, "postgres")
    47  		assert.ErrorContains(t, err, "invalid port (outside range)")
    48  		_, err = ConnectLocalPostgres(context.Background(), Config.Hostname, 65536, "postgres")
    49  		assert.ErrorContains(t, err, `invalid port (strconv.ParseUint: parsing "65536": value out of range)`)
    50  	})
    51  }