github.com/tompao/docker@v1.9.1/pkg/fileutils/fileutils_test.go (about)

     1  package fileutils
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"path"
     7  	"path/filepath"
     8  	"testing"
     9  )
    10  
    11  // CopyFile with invalid src
    12  func TestCopyFileWithInvalidSrc(t *testing.T) {
    13  	tempFolder, err := ioutil.TempDir("", "docker-fileutils-test")
    14  	defer os.RemoveAll(tempFolder)
    15  	if err != nil {
    16  		t.Fatal(err)
    17  	}
    18  	bytes, err := CopyFile("/invalid/file/path", path.Join(tempFolder, "dest"))
    19  	if err == nil {
    20  		t.Fatal("Should have fail to copy an invalid src file")
    21  	}
    22  	if bytes != 0 {
    23  		t.Fatal("Should have written 0 bytes")
    24  	}
    25  
    26  }
    27  
    28  // CopyFile with invalid dest
    29  func TestCopyFileWithInvalidDest(t *testing.T) {
    30  	tempFolder, err := ioutil.TempDir("", "docker-fileutils-test")
    31  	defer os.RemoveAll(tempFolder)
    32  	if err != nil {
    33  		t.Fatal(err)
    34  	}
    35  	src := path.Join(tempFolder, "file")
    36  	err = ioutil.WriteFile(src, []byte("content"), 0740)
    37  	if err != nil {
    38  		t.Fatal(err)
    39  	}
    40  	bytes, err := CopyFile(src, path.Join(tempFolder, "/invalid/dest/path"))
    41  	if err == nil {
    42  		t.Fatal("Should have fail to copy an invalid src file")
    43  	}
    44  	if bytes != 0 {
    45  		t.Fatal("Should have written 0 bytes")
    46  	}
    47  
    48  }
    49  
    50  // CopyFile with same src and dest
    51  func TestCopyFileWithSameSrcAndDest(t *testing.T) {
    52  	tempFolder, err := ioutil.TempDir("", "docker-fileutils-test")
    53  	defer os.RemoveAll(tempFolder)
    54  	if err != nil {
    55  		t.Fatal(err)
    56  	}
    57  	file := path.Join(tempFolder, "file")
    58  	err = ioutil.WriteFile(file, []byte("content"), 0740)
    59  	if err != nil {
    60  		t.Fatal(err)
    61  	}
    62  	bytes, err := CopyFile(file, file)
    63  	if err != nil {
    64  		t.Fatal(err)
    65  	}
    66  	if bytes != 0 {
    67  		t.Fatal("Should have written 0 bytes as it is the same file.")
    68  	}
    69  }
    70  
    71  // CopyFile with same src and dest but path is different and not clean
    72  func TestCopyFileWithSameSrcAndDestWithPathNameDifferent(t *testing.T) {
    73  	tempFolder, err := ioutil.TempDir("", "docker-fileutils-test")
    74  	defer os.RemoveAll(tempFolder)
    75  	if err != nil {
    76  		t.Fatal(err)
    77  	}
    78  	testFolder := path.Join(tempFolder, "test")
    79  	err = os.MkdirAll(testFolder, 0740)
    80  	if err != nil {
    81  		t.Fatal(err)
    82  	}
    83  	file := path.Join(testFolder, "file")
    84  	sameFile := testFolder + "/../test/file"
    85  	err = ioutil.WriteFile(file, []byte("content"), 0740)
    86  	if err != nil {
    87  		t.Fatal(err)
    88  	}
    89  	bytes, err := CopyFile(file, sameFile)
    90  	if err != nil {
    91  		t.Fatal(err)
    92  	}
    93  	if bytes != 0 {
    94  		t.Fatal("Should have written 0 bytes as it is the same file.")
    95  	}
    96  }
    97  
    98  func TestCopyFile(t *testing.T) {
    99  	tempFolder, err := ioutil.TempDir("", "docker-fileutils-test")
   100  	defer os.RemoveAll(tempFolder)
   101  	if err != nil {
   102  		t.Fatal(err)
   103  	}
   104  	src := path.Join(tempFolder, "src")
   105  	dest := path.Join(tempFolder, "dest")
   106  	ioutil.WriteFile(src, []byte("content"), 0777)
   107  	ioutil.WriteFile(dest, []byte("destContent"), 0777)
   108  	bytes, err := CopyFile(src, dest)
   109  	if err != nil {
   110  		t.Fatal(err)
   111  	}
   112  	if bytes != 7 {
   113  		t.Fatalf("Should have written %d bytes but wrote %d", 7, bytes)
   114  	}
   115  	actual, err := ioutil.ReadFile(dest)
   116  	if err != nil {
   117  		t.Fatal(err)
   118  	}
   119  	if string(actual) != "content" {
   120  		t.Fatalf("Dest content was '%s', expected '%s'", string(actual), "content")
   121  	}
   122  }
   123  
   124  // Reading a symlink to a directory must return the directory
   125  func TestReadSymlinkedDirectoryExistingDirectory(t *testing.T) {
   126  	var err error
   127  	if err = os.Mkdir("/tmp/testReadSymlinkToExistingDirectory", 0777); err != nil {
   128  		t.Errorf("failed to create directory: %s", err)
   129  	}
   130  
   131  	if err = os.Symlink("/tmp/testReadSymlinkToExistingDirectory", "/tmp/dirLinkTest"); err != nil {
   132  		t.Errorf("failed to create symlink: %s", err)
   133  	}
   134  
   135  	var path string
   136  	if path, err = ReadSymlinkedDirectory("/tmp/dirLinkTest"); err != nil {
   137  		t.Fatalf("failed to read symlink to directory: %s", err)
   138  	}
   139  
   140  	if path != "/tmp/testReadSymlinkToExistingDirectory" {
   141  		t.Fatalf("symlink returned unexpected directory: %s", path)
   142  	}
   143  
   144  	if err = os.Remove("/tmp/testReadSymlinkToExistingDirectory"); err != nil {
   145  		t.Errorf("failed to remove temporary directory: %s", err)
   146  	}
   147  
   148  	if err = os.Remove("/tmp/dirLinkTest"); err != nil {
   149  		t.Errorf("failed to remove symlink: %s", err)
   150  	}
   151  }
   152  
   153  // Reading a non-existing symlink must fail
   154  func TestReadSymlinkedDirectoryNonExistingSymlink(t *testing.T) {
   155  	var path string
   156  	var err error
   157  	if path, err = ReadSymlinkedDirectory("/tmp/test/foo/Non/ExistingPath"); err == nil {
   158  		t.Fatalf("error expected for non-existing symlink")
   159  	}
   160  
   161  	if path != "" {
   162  		t.Fatalf("expected empty path, but '%s' was returned", path)
   163  	}
   164  }
   165  
   166  // Reading a symlink to a file must fail
   167  func TestReadSymlinkedDirectoryToFile(t *testing.T) {
   168  	var err error
   169  	var file *os.File
   170  
   171  	if file, err = os.Create("/tmp/testReadSymlinkToFile"); err != nil {
   172  		t.Fatalf("failed to create file: %s", err)
   173  	}
   174  
   175  	file.Close()
   176  
   177  	if err = os.Symlink("/tmp/testReadSymlinkToFile", "/tmp/fileLinkTest"); err != nil {
   178  		t.Errorf("failed to create symlink: %s", err)
   179  	}
   180  
   181  	var path string
   182  	if path, err = ReadSymlinkedDirectory("/tmp/fileLinkTest"); err == nil {
   183  		t.Fatalf("ReadSymlinkedDirectory on a symlink to a file should've failed")
   184  	}
   185  
   186  	if path != "" {
   187  		t.Fatalf("path should've been empty: %s", path)
   188  	}
   189  
   190  	if err = os.Remove("/tmp/testReadSymlinkToFile"); err != nil {
   191  		t.Errorf("failed to remove file: %s", err)
   192  	}
   193  
   194  	if err = os.Remove("/tmp/fileLinkTest"); err != nil {
   195  		t.Errorf("failed to remove symlink: %s", err)
   196  	}
   197  }
   198  
   199  func TestWildcardMatches(t *testing.T) {
   200  	match, _ := Matches("fileutils.go", []string{"*"})
   201  	if match != true {
   202  		t.Errorf("failed to get a wildcard match, got %v", match)
   203  	}
   204  }
   205  
   206  // A simple pattern match should return true.
   207  func TestPatternMatches(t *testing.T) {
   208  	match, _ := Matches("fileutils.go", []string{"*.go"})
   209  	if match != true {
   210  		t.Errorf("failed to get a match, got %v", match)
   211  	}
   212  }
   213  
   214  // An exclusion followed by an inclusion should return true.
   215  func TestExclusionPatternMatchesPatternBefore(t *testing.T) {
   216  	match, _ := Matches("fileutils.go", []string{"!fileutils.go", "*.go"})
   217  	if match != true {
   218  		t.Errorf("failed to get true match on exclusion pattern, got %v", match)
   219  	}
   220  }
   221  
   222  // A folder pattern followed by an exception should return false.
   223  func TestPatternMatchesFolderExclusions(t *testing.T) {
   224  	match, _ := Matches("docs/README.md", []string{"docs", "!docs/README.md"})
   225  	if match != false {
   226  		t.Errorf("failed to get a false match on exclusion pattern, got %v", match)
   227  	}
   228  }
   229  
   230  // A folder pattern followed by an exception should return false.
   231  func TestPatternMatchesFolderWithSlashExclusions(t *testing.T) {
   232  	match, _ := Matches("docs/README.md", []string{"docs/", "!docs/README.md"})
   233  	if match != false {
   234  		t.Errorf("failed to get a false match on exclusion pattern, got %v", match)
   235  	}
   236  }
   237  
   238  // A folder pattern followed by an exception should return false.
   239  func TestPatternMatchesFolderWildcardExclusions(t *testing.T) {
   240  	match, _ := Matches("docs/README.md", []string{"docs/*", "!docs/README.md"})
   241  	if match != false {
   242  		t.Errorf("failed to get a false match on exclusion pattern, got %v", match)
   243  	}
   244  }
   245  
   246  // A pattern followed by an exclusion should return false.
   247  func TestExclusionPatternMatchesPatternAfter(t *testing.T) {
   248  	match, _ := Matches("fileutils.go", []string{"*.go", "!fileutils.go"})
   249  	if match != false {
   250  		t.Errorf("failed to get false match on exclusion pattern, got %v", match)
   251  	}
   252  }
   253  
   254  // A filename evaluating to . should return false.
   255  func TestExclusionPatternMatchesWholeDirectory(t *testing.T) {
   256  	match, _ := Matches(".", []string{"*.go"})
   257  	if match != false {
   258  		t.Errorf("failed to get false match on ., got %v", match)
   259  	}
   260  }
   261  
   262  // A single ! pattern should return an error.
   263  func TestSingleExclamationError(t *testing.T) {
   264  	_, err := Matches("fileutils.go", []string{"!"})
   265  	if err == nil {
   266  		t.Errorf("failed to get an error for a single exclamation point, got %v", err)
   267  	}
   268  }
   269  
   270  // A string preceded with a ! should return true from Exclusion.
   271  func TestExclusion(t *testing.T) {
   272  	exclusion := exclusion("!")
   273  	if !exclusion {
   274  		t.Errorf("failed to get true for a single !, got %v", exclusion)
   275  	}
   276  }
   277  
   278  // Matches with no patterns
   279  func TestMatchesWithNoPatterns(t *testing.T) {
   280  	matches, err := Matches("/any/path/there", []string{})
   281  	if err != nil {
   282  		t.Fatal(err)
   283  	}
   284  	if matches {
   285  		t.Fatalf("Should not have match anything")
   286  	}
   287  }
   288  
   289  // Matches with malformed patterns
   290  func TestMatchesWithMalformedPatterns(t *testing.T) {
   291  	matches, err := Matches("/any/path/there", []string{"["})
   292  	if err == nil {
   293  		t.Fatal("Should have failed because of a malformed syntax in the pattern")
   294  	}
   295  	if matches {
   296  		t.Fatalf("Should not have match anything")
   297  	}
   298  }
   299  
   300  // An empty string should return true from Empty.
   301  func TestEmpty(t *testing.T) {
   302  	empty := empty("")
   303  	if !empty {
   304  		t.Errorf("failed to get true for an empty string, got %v", empty)
   305  	}
   306  }
   307  
   308  func TestCleanPatterns(t *testing.T) {
   309  	cleaned, _, _, _ := CleanPatterns([]string{"docs", "config"})
   310  	if len(cleaned) != 2 {
   311  		t.Errorf("expected 2 element slice, got %v", len(cleaned))
   312  	}
   313  }
   314  
   315  func TestCleanPatternsStripEmptyPatterns(t *testing.T) {
   316  	cleaned, _, _, _ := CleanPatterns([]string{"docs", "config", ""})
   317  	if len(cleaned) != 2 {
   318  		t.Errorf("expected 2 element slice, got %v", len(cleaned))
   319  	}
   320  }
   321  
   322  func TestCleanPatternsExceptionFlag(t *testing.T) {
   323  	_, _, exceptions, _ := CleanPatterns([]string{"docs", "!docs/README.md"})
   324  	if !exceptions {
   325  		t.Errorf("expected exceptions to be true, got %v", exceptions)
   326  	}
   327  }
   328  
   329  func TestCleanPatternsLeadingSpaceTrimmed(t *testing.T) {
   330  	_, _, exceptions, _ := CleanPatterns([]string{"docs", "  !docs/README.md"})
   331  	if !exceptions {
   332  		t.Errorf("expected exceptions to be true, got %v", exceptions)
   333  	}
   334  }
   335  
   336  func TestCleanPatternsTrailingSpaceTrimmed(t *testing.T) {
   337  	_, _, exceptions, _ := CleanPatterns([]string{"docs", "!docs/README.md  "})
   338  	if !exceptions {
   339  		t.Errorf("expected exceptions to be true, got %v", exceptions)
   340  	}
   341  }
   342  
   343  func TestCleanPatternsErrorSingleException(t *testing.T) {
   344  	_, _, _, err := CleanPatterns([]string{"!"})
   345  	if err == nil {
   346  		t.Errorf("expected error on single exclamation point, got %v", err)
   347  	}
   348  }
   349  
   350  func TestCleanPatternsFolderSplit(t *testing.T) {
   351  	_, dirs, _, _ := CleanPatterns([]string{"docs/config/CONFIG.md"})
   352  	if dirs[0][0] != "docs" {
   353  		t.Errorf("expected first element in dirs slice to be docs, got %v", dirs[0][1])
   354  	}
   355  	if dirs[0][1] != "config" {
   356  		t.Errorf("expected first element in dirs slice to be config, got %v", dirs[0][1])
   357  	}
   358  }
   359  
   360  func TestCreateIfNotExistsDir(t *testing.T) {
   361  	tempFolder, err := ioutil.TempDir("", "docker-fileutils-test")
   362  	if err != nil {
   363  		t.Fatal(err)
   364  	}
   365  	defer os.RemoveAll(tempFolder)
   366  
   367  	folderToCreate := filepath.Join(tempFolder, "tocreate")
   368  
   369  	if err := CreateIfNotExists(folderToCreate, true); err != nil {
   370  		t.Fatal(err)
   371  	}
   372  	fileinfo, err := os.Stat(folderToCreate)
   373  	if err != nil {
   374  		t.Fatalf("Should have create a folder, got %v", err)
   375  	}
   376  
   377  	if !fileinfo.IsDir() {
   378  		t.Fatalf("Should have been a dir, seems it's not")
   379  	}
   380  }
   381  
   382  func TestCreateIfNotExistsFile(t *testing.T) {
   383  	tempFolder, err := ioutil.TempDir("", "docker-fileutils-test")
   384  	if err != nil {
   385  		t.Fatal(err)
   386  	}
   387  	defer os.RemoveAll(tempFolder)
   388  
   389  	fileToCreate := filepath.Join(tempFolder, "file/to/create")
   390  
   391  	if err := CreateIfNotExists(fileToCreate, false); err != nil {
   392  		t.Fatal(err)
   393  	}
   394  	fileinfo, err := os.Stat(fileToCreate)
   395  	if err != nil {
   396  		t.Fatalf("Should have create a file, got %v", err)
   397  	}
   398  
   399  	if fileinfo.IsDir() {
   400  		t.Fatalf("Should have been a file, seems it's not")
   401  	}
   402  }