Skip to content

Commit

Permalink
Merge pull request #165 from moov-io/use-connection-helper
Browse files Browse the repository at this point in the history
fix: use the connection() helper to check for network errors
  • Loading branch information
adamdecaf authored Aug 30, 2023
2 parents c5f6628 + 8153767 commit c8a328e
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 3 deletions.
16 changes: 13 additions & 3 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -377,8 +377,13 @@ func (c *client) UploadFile(path string, contents io.ReadCloser) error {
// appear on the server.
func (c *client) ListFiles(dir string) ([]string, error) {
pattern := filepath.Clean(strings.TrimPrefix(dir, string(os.PathSeparator)))

conn, err := c.connection()
if err != nil {
return nil, err
}

wd := "."
var err error
switch {
case dir == "/":
pattern = "*"
Expand All @@ -390,7 +395,7 @@ func (c *client) ListFiles(dir string) ([]string, error) {
}
case pattern != "":
pattern = "[/?]" + pattern + "/*"
wd, err = c.client.Getwd()
wd, err = conn.Getwd()
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -498,7 +503,12 @@ func (c *client) Walk(dir string, fn fs.WalkDirFunc) error {
c.mu.Lock()
defer c.mu.Unlock()

w := c.client.Walk(dir)
conn, err := c.connection()
if err != nil {
return err
}

w := conn.Walk(dir)
if w == nil {
return errors.New("nil *fs.Walker")
}
Expand Down
54 changes: 54 additions & 0 deletions network_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Copyright 2022 The Moov Authors
// Use of this source code is governed by an Apache License
// license that can be found in the LICENSE file.

package go_sftp_test

import (
"testing"
"time"

"github.com/moov-io/base/log"
sftp "github.com/moov-io/go-sftp"
"github.com/stretchr/testify/require"
)

func TestNetwork(t *testing.T) {
if testing.Short() {
t.Skip("-short flag was provided")
}

client, err := sftp.NewClient(log.NewTestLogger(), &sftp.ClientConfig{
Hostname: "localhost:2222",
Username: "demo",
Password: "password",
Timeout: 5 * time.Second,
MaxConnections: 1,
PacketSize: 32000,
})
require.NoError(t, err)
t.Cleanup(func() {
require.NoError(t, client.Close())
})

t.Run("Ping", func(t *testing.T) {
require.NoError(t, client.Ping())
})

t.Run("Read after Closing", func(t *testing.T) {
// Close the connection but have the caller try without knowing it's closed
require.NoError(t, client.Close())

files, err := client.ListFiles("/outbox")
require.NoError(t, err)
require.Greater(t, len(files), 0)

// close it again for fun
require.NoError(t, client.Close())

// try again
files, err = client.ListFiles("/outbox")
require.NoError(t, err)
require.Greater(t, len(files), 0)
})
}

0 comments on commit c8a328e

Please sign in to comment.