github.com/demonoid81/moby@v0.0.0-20200517203328-62dd8e17c460/pkg/system/rm_test.go (about)

     1  package system // import "github.com/demonoid81/moby/pkg/system"
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"path/filepath"
     7  	"runtime"
     8  	"testing"
     9  	"time"
    10  
    11  	"github.com/moby/sys/mount"
    12  	"gotest.tools/v3/skip"
    13  )
    14  
    15  func TestEnsureRemoveAllNotExist(t *testing.T) {
    16  	// should never return an error for a non-existent path
    17  	if err := EnsureRemoveAll("/non/existent/path"); err != nil {
    18  		t.Fatal(err)
    19  	}
    20  }
    21  
    22  func TestEnsureRemoveAllWithDir(t *testing.T) {
    23  	dir, err := ioutil.TempDir("", "test-ensure-removeall-with-dir")
    24  	if err != nil {
    25  		t.Fatal(err)
    26  	}
    27  	if err := EnsureRemoveAll(dir); err != nil {
    28  		t.Fatal(err)
    29  	}
    30  }
    31  
    32  func TestEnsureRemoveAllWithFile(t *testing.T) {
    33  	tmp, err := ioutil.TempFile("", "test-ensure-removeall-with-dir")
    34  	if err != nil {
    35  		t.Fatal(err)
    36  	}
    37  	tmp.Close()
    38  	if err := EnsureRemoveAll(tmp.Name()); err != nil {
    39  		t.Fatal(err)
    40  	}
    41  }
    42  
    43  func TestEnsureRemoveAllWithMount(t *testing.T) {
    44  	skip.If(t, runtime.GOOS == "windows", "mount not supported on Windows")
    45  	skip.If(t, os.Getuid() != 0, "skipping test that requires root")
    46  
    47  	dir1, err := ioutil.TempDir("", "test-ensure-removeall-with-dir1")
    48  	if err != nil {
    49  		t.Fatal(err)
    50  	}
    51  	dir2, err := ioutil.TempDir("", "test-ensure-removeall-with-dir2")
    52  	if err != nil {
    53  		t.Fatal(err)
    54  	}
    55  	defer os.RemoveAll(dir2)
    56  
    57  	bindDir := filepath.Join(dir1, "bind")
    58  	if err := os.MkdirAll(bindDir, 0755); err != nil {
    59  		t.Fatal(err)
    60  	}
    61  
    62  	if err := mount.Mount(dir2, bindDir, "none", "bind"); err != nil {
    63  		t.Fatal(err)
    64  	}
    65  
    66  	done := make(chan struct{})
    67  	go func() {
    68  		err = EnsureRemoveAll(dir1)
    69  		close(done)
    70  	}()
    71  
    72  	select {
    73  	case <-done:
    74  		if err != nil {
    75  			t.Fatal(err)
    76  		}
    77  	case <-time.After(5 * time.Second):
    78  		t.Fatal("timeout waiting for EnsureRemoveAll to finish")
    79  	}
    80  
    81  	if _, err := os.Stat(dir1); !os.IsNotExist(err) {
    82  		t.Fatalf("expected %q to not exist", dir1)
    83  	}
    84  }