Adding Tests to test the func & resolving comment

This commit is contained in:
tanishq.singhal 2023-05-15 11:43:30 +05:30
parent 0ac5f90dbb
commit 628da3e118
2 changed files with 55 additions and 11 deletions

View File

@ -924,19 +924,19 @@ func (c *Client) MkdirAll(path string) error {
return nil
}
// DeleteAllResources delete files recursively in the directory and Recursively delete subdirectories.
// RemoveAll delete files recursively in the directory and Recursively delete subdirectories.
// An error will be returned if no file or directory with the specified path exists
func (c *Client) DeleteAllResources(filePath string) error {
func (c *Client) RemoveAll(path string) error {
// Get the file/directory information
fileInfo, err := c.Stat(filePath)
fi, err := c.Stat(path)
if err != nil {
return err
}
if fileInfo.IsDir() {
if fi.IsDir() {
// Delete files recursively in the directory
files, err := c.ReadDir(filePath)
files, err := c.ReadDir(path)
if err != nil {
return err
}
@ -944,13 +944,13 @@ func (c *Client) DeleteAllResources(filePath string) error {
for _, file := range files {
if file.IsDir() {
// Recursively delete subdirectories
err = c.DeleteAllResources(filePath + "/" + file.Name())
err = c.RemoveAll(path + "/" + file.Name())
if err != nil {
return err
}
} else {
// Delete individual files
err = c.Remove(filePath + "/" + file.Name())
err = c.Remove(path + "/" + file.Name())
if err != nil {
return err
}
@ -958,15 +958,15 @@ func (c *Client) DeleteAllResources(filePath string) error {
}
// Delete the empty directory
err = c.RemoveDirectory(filePath)
err = c.RemoveDirectory(path)
if err != nil {
return err
return c.RemoveDirectory(path)
}
} else {
// Delete individual files
err = c.Remove(filePath)
err = c.Remove(path)
if err != nil {
return err
return c.Remove(path)
}
}

View File

@ -651,6 +651,50 @@ func TestClientRemove(t *testing.T) {
}
}
func TestRemoveAll(t *testing.T) {
sftp, cmd := testClient(t, READWRITE, NODELAY)
defer cmd.Wait()
defer sftp.Close()
// Create a temporary directory for testing
tempDir, err := ioutil.TempDir("", "sftptest-removeAll")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tempDir)
// Create file and directory within the temporary directory
f, err := ioutil.TempFile(tempDir, "sftptest-removeAll*.txt")
if err != nil {
t.Fatal(err)
}
defer f.Close()
d, err := ioutil.TempDir(tempDir, "sftptest-removeAll1")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(d)
// Call the function to remove the files recursively
err = sftp.RemoveAll(tempDir)
if err != nil {
t.Fatal(err)
}
// Check if the directories and files have been deleted
_, err = os.Stat(f.Name())
if !os.IsNotExist(err) {
t.Errorf("File %s still exists", f.Name())
}
_, err = os.Stat(d)
if !os.IsNotExist(err) {
t.Errorf("Directory %s still exists", d)
}
}
func TestClientRemoveDir(t *testing.T) {
sftp, cmd := testClient(t, READWRITE, NODELAY)
defer cmd.Wait()