github.com/amacneil/dbmate@v1.16.3-0.20230225174651-ca89b10d75d7/main_test.go (about)

     1  package main
     2  
     3  import (
     4  	"flag"
     5  	"os"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/require"
     9  	"github.com/urfave/cli/v2"
    10  )
    11  
    12  func TestGetDatabaseUrl(t *testing.T) {
    13  	// set environment variables
    14  	require.NoError(t, os.Setenv("DATABASE_URL", "foo://example.org/one"))
    15  	require.NoError(t, os.Setenv("CUSTOM_URL", "foo://example.org/two"))
    16  
    17  	app := NewApp()
    18  	flagset := flag.NewFlagSet(app.Name, flag.ContinueOnError)
    19  	for _, f := range app.Flags {
    20  		require.NoError(t, f.Apply(flagset))
    21  	}
    22  	ctx := cli.NewContext(app, flagset, nil)
    23  
    24  	// no flags defaults to DATABASE_URL
    25  	u, err := getDatabaseURL(ctx)
    26  	require.NoError(t, err)
    27  	require.Equal(t, "foo://example.org/one", u.String())
    28  
    29  	// --env overwrites DATABASE_URL
    30  	require.NoError(t, ctx.Set("env", "CUSTOM_URL"))
    31  	u, err = getDatabaseURL(ctx)
    32  	require.NoError(t, err)
    33  	require.Equal(t, "foo://example.org/two", u.String())
    34  
    35  	// --url takes precedence over preceding two options
    36  	require.NoError(t, ctx.Set("url", "foo://example.org/three"))
    37  	u, err = getDatabaseURL(ctx)
    38  	require.NoError(t, err)
    39  	require.Equal(t, "foo://example.org/three", u.String())
    40  }
    41  
    42  func TestRedactLogString(t *testing.T) {
    43  	examples := []struct {
    44  		in       string
    45  		expected string
    46  	}{
    47  		{"normal string",
    48  			"normal string"},
    49  		// malformed URL example (note forward slash in password)
    50  		{"parse \"mysql://username:otS33+tb/e4=@localhost:3306/database\": invalid",
    51  			"parse \"mysql://username:********@localhost:3306/database\": invalid"},
    52  		// invalid port, but probably not a password since there is no @
    53  		{"parse \"mysql://localhost:abc/database\": invalid",
    54  			"parse \"mysql://localhost:abc/database\": invalid"},
    55  	}
    56  
    57  	for _, ex := range examples {
    58  		require.Equal(t, ex.expected, redactLogString(ex.in))
    59  	}
    60  }