github.com/adevinta/maiao@v0.0.0-20240318133227-b6f9656b5e07/pkg/credentials/netrc_test.go (about)

     1  package credentials
     2  
     3  import (
     4  	"fmt"
     5  	"os/user"
     6  	"strings"
     7  	"testing"
     8  
     9  	"github.com/stretchr/testify/assert"
    10  	"github.com/adevinta/maiao/pkg/system"
    11  )
    12  
    13  func testCredentialSuccess(t *testing.T, n *Netrc, machine string, expected Credentials) {
    14  	fmt.Println(n.Path)
    15  	c, err := n.CredentialForHost(machine)
    16  	assert.NoError(t, err)
    17  	assert.NotNil(t, c)
    18  	assert.Equal(t, expected, *c)
    19  }
    20  
    21  func TestNetrcCredentials(t *testing.T) {
    22  	var n *Netrc
    23  	t.Run("when netrc handler is null, an error is returned", func(t *testing.T) {
    24  		c, err := n.CredentialForHost("some host")
    25  		assert.Error(t, err)
    26  		assert.Nil(t, c)
    27  	})
    28  	n = &Netrc{}
    29  	t.Run("when failing to get current user, an error is returned", func(t *testing.T) {
    30  		t.Cleanup(system.Reset)
    31  		system.CurrentUser = func() (*user.User, error) {
    32  			return nil, fmt.Errorf("test error")
    33  		}
    34  		c, err := n.CredentialForHost("some host")
    35  		assert.Error(t, err)
    36  		assert.Nil(t, c)
    37  	})
    38  	n.CredentialForHost("some host")
    39  	t.Run("when no path is provided, a default one is created", func(t *testing.T) {
    40  		if !strings.HasSuffix(n.Path, "/.netrc") {
    41  			t.Errorf("default path %s does not have the /.netrc suffix", n.Path)
    42  		}
    43  	})
    44  	n.Path = "resources/.netrc"
    45  	t.Run("when a path is provided", func(t *testing.T) {
    46  		t.Run("and the machine has only login, credentials is returned", func(t *testing.T) {
    47  			testCredentialSuccess(t, n, "login.example.com", Credentials{Username: "this-is-a-login"})
    48  		})
    49  		t.Run("and the machine has only password, credentials is returned", func(t *testing.T) {
    50  			testCredentialSuccess(t, n, "password.example.com", Credentials{Password: "pass"})
    51  		})
    52  		t.Run("and the machine has login and password, credentials is returned", func(t *testing.T) {
    53  			testCredentialSuccess(t, n, "example.com", Credentials{Username: "me", Password: "a-secure-password"})
    54  		})
    55  		t.Run("when the path does not exist, an eror is returned", func(t *testing.T) {
    56  			n.Path = "unavailable file"
    57  			c, err := n.CredentialForHost("any")
    58  			assert.Error(t, err)
    59  			assert.Nil(t, c)
    60  		})
    61  	})
    62  }